mysql sql語句中用括號處理or和and的運算順序


需求,我要檢索出 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 );


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM