Home > Database > Mysql Tutorial > body text

SQL中 and or优先级问题

WBOY
Release: 2016-06-07 17:12:27
Original
1256 people have browsed it

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template