码迷,mamicode.com
首页 > 数据库 > 详细

mysql sql语句中用括号处理or和and的运算顺序

时间:2015-04-01 17:34:07      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

需求,我要检索出 a =1 或者 b=1 并且 c = 0 或者 c=1 时候的结果

例子:

select * from test where a = 1 or b = 1 and ( c = 0 or c = 1)

这里会检索 a=1 或者 b=1 的结果集,再过滤掉出其中 c=0 或者 c=1 的结果

如果我们换个写法

select * from test where a = 1 or b = 1 and c = 0 or c = 1

这样会检索 a=1 或者 b =1 或者 c=1的结果集,再过滤出其中 c=0的结果,这个不是我期望的,所以用括号括起来调整他们的处理顺序就OK了。

 

 

先筛选同一个医院或同一个科室的用户list,再按照发医说数量和粉丝数再筛选一次用户list,

正确SQL:

SELECT a.* FROM xm_user a WHERE (a.user_hospital = ‘301医院‘ or a.user_department = ‘骨科‘) and a.user_id != 1
and not EXISTS (SELECT b.* FROM xm_user_friendship b WHERE b.fs_from_user_id = 1 and b.fs_to_user_id = a.user_id );

错误SQL:

SELECT a.* FROM xm_user a WHERE  a.user_hospital = ‘301医院‘ or a.user_department = ‘骨科‘ and a.user_id != 1
and not EXISTS (SELECT b.* FROM xm_user_friendship b WHERE b.fs_from_user_id = 1 and b.fs_to_user_id = a.user_id );

mysql sql语句中用括号处理or和and的运算顺序

标签:

原文地址:http://www.cnblogs.com/kenshinobiy/p/4384234.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!