SQL中的and、or

在sql查询语句中长用到and和or,它们在用的时候有些需要注意的地方

不管在一项表达式中有多少个and或or,它是将前一个表达式看作一项,and与or后的所有表达式看做一项。

and的前后都为真的时候才为真,取交集
or有一个为真,即为真,取并集

 select * from users where 1=1;			# 1=1 即全集

在这里插入图片描述

 select * from users where id=1;

在这里插入图片描述

select * from users where id =1 or 1=1 and 1=1 or user_name ="";

执行顺序:

  1. 第一个出现的逻辑运算符是or,所有取得是并集
  2. 所有结果该有id=1的一项
  3. 1=1 and 1=1 or user_name ="",第一个出现的and,取交集
  4. 1=1取全集
  5. 1=1 or user_name ="",or取并集,1=1为真,取全集,所有user_name =""根本不会去判断,所以这一表达式 取全集
  6. 1=1 and 1=1 or user_name ="" → 1=1 and 全集,为全集
  7. id =1 or 1=1 and 1=1 or user_name ="" → id=1 or 全集,取并集,所有最后结果应为全集

在这里插入图片描述

  select * from users where id =1 or 1=1 and 1=2 or user_name ="ccc";
  1. 1=2 or user_name =“ccc”,1=2为假,取并集,为user_name =“ccc”
  2. 1=1 and 1=2 or user_name =“ccc” → 1=1 and user_name =“ccc” 取交集,为user_name =“ccc”
  3. id =1 or 1=1 and 1=2 or user_name ="ccc"→id=1 or user_name =“ccc”,取并集,最后结果显示id=1和user_name ="ccc"这两项数据

在这里插入图片描述select * from users where id='1' or 1=1 and user_name='' or 1=1;

  1. user_name=’’ or 1=1取并集,为全集
  2. 1=1 and user_name=’’ or 1=1→1=1 and 1=1 为全集
  3. id=‘1’ or 1=1 and user_name=’’ or 1=1→id=‘1’ or 1=1取并集,最后输出应该为全集

在这里插入图片描述

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值