在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 ="";
执行顺序:
- 第一个出现的逻辑运算符是or,所有取得是并集
- 所有结果该有id=1的一项
- 1=1 and 1=1 or user_name ="",第一个出现的and,取交集
- 1=1取全集
- 1=1 or user_name ="",or取并集,1=1为真,取全集,所有user_name =""根本不会去判断,所以这一表达式 取全集
- 1=1 and 1=1 or user_name ="" → 1=1 and 全集,为全集
- 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=2 or user_name =“ccc”,1=2为假,取并集,为user_name =“ccc”
- 1=1 and 1=2 or user_name =“ccc” → 1=1 and user_name =“ccc” 取交集,为user_name =“ccc”
- 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;
- user_name=’’ or 1=1取并集,为全集
- 1=1 and user_name=’’ or 1=1→1=1 and 1=1 为全集
- id=‘1’ or 1=1 and user_name=’’ or 1=1→id=‘1’ or 1=1取并集,最后输出应该为全集