Home  >  Article  >  Database  >  SQL中 and or优先级问题

SQL中 and or优先级问题

WBOY
WBOYOriginal
2016-06-07 17:12:271220browse

SQL中 and or优先级问题,where 后面如果有and,or的条件,则or自动会把左右的查询条件分开,即先执行and,再执行or。原因就是:a

刚刚在项目中遇到这样一个问题,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

修改为:

呵呵,发现问题了:

where 后面如果有and,or的条件,则or自动会把左右的查询条件分开,即先执行and,再执行or。原因就是:and的执行优先级最高!

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

问题的解决办法是:

用()来改变执行顺序!!!!

上面我所需要的SQL语句是这样的

这样就是完美的答案了!!!!

linux

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn