SQL中逻辑运算 and or优先级

今天想写一个查询,实现“补加”数据的目的,执行的SQL如下:

select * from table_a where 1=1 and orgcode like '%111111%' or state like '%04%' and eventid like '%222222%'

备注说明:
1、like '%111111%' 能够查询所有数据
2、like '%04%' 能够查询一条数据
3、like '%222222%' 能够查询4条数据

我的目的是想根据like '%222222%'查询4条数据 + like '%04%'查询1条数据 = 5条数据;结果执行上面这个SQL查询出了所有的数据,

最后查找原因是——and的优先级比or的优先级高;上面的SQL实际等价于

select * from table_a where 1=1 and orgcode like '%111111%' or (state like '%04%' and eventid like '%222222%')

如果想达到“筛选”的目的,可以如下改

select * from table_a where 1=1 and orgcode like '%111111%'  and eventid like '%222222%' or state like '%04%'

关系型运算符优先级高到低为:not and or

备注:为了改变逻辑运算符的顺序,我们也可以使用()区分,它的优先级是最高的

猜你喜欢

转载自hbiao68.iteye.com/blog/1825842