小编典典

SQL中布尔表达式的求值顺序

sql

我在弄清楚SQL中布尔谓词的求值顺序时遇到了麻烦。

在我们的(虚拟)汽车数据库中考虑以下选择谓词:

WHERE
make='Honda' AND model='Accord' OR make='VW' AND model='Golf';

我知道AND的优先级高于OR,但是如果此表达式的计算方式如下,我会感到困惑:

((make='Honda' AND model='Accord') OR make='VW') AND model='Golf';

或为:

(make='Honda' AND model='Accord') OR (make='VW' AND model='Golf');

还是完全不同的东西?

非常感谢您的帮助。


阅读 269

收藏
2021-04-14

共1个答案

小编典典

应该像这样评估

WHERE
(make='Honda' AND model='Accord' ) OR (make='VW' AND model='Golf');

说明: 在SQL Server中AND具有优先权OR,因此您可以想象AND部件位于括号内,并在它们之后和之后进行求值,或者

根据您的评论的详细信息

AND优先于OR,这是我在帖子中已经提到的。此优先级为“从左到右”,因此仍不清楚在此执行哪个评估顺序:((make =’Honda’AND model
=’Accord’)OR make =’VW’)AND model =’Golf’; 或(make =’Honda’AND model
=’Accord’)或(make =’VW’AND model =’Golf’); 『。

L2R解析

  1. WHERE (make='Honda' AND model='Accord') OR make='VW' AND model='Golf';

因为首先所有AND和最左边

  1. WHERE结果1OR (make='VW' AND model='Golf');

因为首先所有AND

  1. WHEREresult1 ORresult2;

最终或

R2L解析

  1. WHERE make='Honda' AND model='Accord' OR (make='VW' AND model='Golf');

因为首先是所有AND,然后是最右边的AND

  1. WHERE (make='Honda' AND model='Accord') OR结果1;

因为首先所有AND都经过OR

  1. WHEREresult2 ORresult1;

最终或

因此,在两种情况下,条件评估为

WHERE
(make='Honda' AND model='Accord' ) OR (make='VW' AND model='Golf');

所以我在下面的查询中评估了所有三个表达式

   -- create table t(make varchar(100), model varchar(100))
   -- insert into t values ('Honda','Golf'),('Honda','Accord'),('VW','Golf'),('VW','Accord')
    select *, 
    case when make='Honda' AND model='Accord' OR make='VW' AND model='Golf' then 1 else 0 end as result,
    case when (make='Honda' AND model='Accord') OR (make='VW' AND model='Golf') then 1 else 0 end as result1,
    case when ((make='Honda' AND model='Accord') OR make='VW' ) AND model='Golf' then 1 else 0 end as result2
    from t
    ;

结果表明,它result =result1始终在被证明为

WHERE
(make='Honda' AND model='Accord' ) OR (make='VW' AND model='Golf');
2021-04-14