当没有指定括号时,如何将混合的AND和OR嵌套在SQL中?

时间:2016-01-25 19:34:43

标签: sql

在这个SQL中:

select * from cars
where brand='VW' or year=1974 and active=true or active is null

常见数据库引擎如何嵌套运算符,而不是键入括号?

我的意思是,像(brand='VW' or year=1974) and (active=true or active is null)

或者brand='VW' or (year=1974 and active=true) or active is null

1 个答案:

答案 0 :(得分:1)

AND高于OR。见https://docs.oracle.com/cd/E17952_01/refman-5.1-en/operator-precedence.html

该网站列出了运营商优先级:

INTERVAL
BINARY, COLLATE
!
- (unary minus), ~ (unary bit inversion)
^
*, /, DIV, %, MOD
-, +
<<, >>
&
|
= (comparison), <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN
BETWEEN, CASE, WHEN, THEN, ELSE
NOT
AND, &&
XOR
OR, ||
= (assignment), :=

在您的示例中,

where brand='VW' or year=1974 and active=true or active is null

将首先使用IS,然后是AND,以及最后的OR,如下所示:

where (brand='VW' or (year=1974 and active=true)) or (active is null)