SQL中 and or優先順序問題

來源:互聯網
上載者:User

剛剛在項目中遇到這樣一個問題,SQL語句如下:

select * from LOAN_BACK_LIBRARY where LIBRARY_ID=1 or LIB_ID=1 and STATUS=3

我想要的結果的條件是:1. LIBRARY_ID=1 或者 LIB_ID=1

                                       2.STATUS=3

但是結果並非如此,出現了STATUS!=3的結果,但是卻匹配了 LIBRARY_ID=1 or LIB_ID=1

為什麼呢

原來這個SQL的執行是這樣的:

select * from LOAN_BACK_LIBRARY where LIBRARY_ID=1 or LIB_ID=1 and STATUS=3

修改為:

select * from LOAN_BACK_LIBRARY where STATUS=3 and LIBRARY_ID=1 or LIB_ID=1 依然不正確

呵呵,發現問題了:

where 後面如果有and,or的條件,則or自動會把左右的查詢條件分開,即先執行and,再執行or。原因就是:and的執行優先順序最高!

關係型運算子優先順序高到低為:not and or

問題的解決辦法是:

用()來改變執行順序!!!!

上面我所需要的SQL語句是這樣的

select * from LOAN_BACK_LIBRARY where STATUS=3 and (LIBRARY_ID=1 or LIB_ID=1 )

這樣就是完美的答案了!!!!

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.