sql - SQL 中 bool 表达式的求值顺序

标签 sql

我无法确定 SQL 中 bool 谓词的求值顺序。

考虑以下对我们(假想的)汽车数据库的选择谓词:

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');

或者完全不同的东西?!

非常感谢您的帮助。

最佳答案

这应该被评估为

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

说明:在SQL服务器中AND has precedence over OR因此你可以想象 AND 部分在括号内并在它们之前和之后评估 OR

基于您的评论的详细信息

AND has percedence over OR, it something I already mentioned in my post. This precedence is Left tor Right, therefore it is still not clear which evaluation order takes place here: ((make='Honda' AND model='Accord') OR make='VW') AND model='Golf'; or (make='Honda' AND model='Accord' ) OR (make='VW' AND model='Golf'); –

L2R 解析

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

因为首先所有的 AND 和最左边的

  1. WHEREresult1OR (make='VW' AND model='Golf');

因为首先所有的 AND

  1. WHEREresult1ORresult2;

最后或

R2L 解析

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

因为首先是所有的 AND 和最右边的 AND 第一个

  1. WHERE (make='Honda' AND model='Accord') 或result1;

因为首先所有的 AND 都超过 OR

  1. WHEREresult2ORresult1;

最后或

所以在这两种情况下,条件的计算结果都是

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');

See sqlfiddle demo

关于sql - SQL 中 bool 表达式的求值顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36595640/

相关文章:

sql - 在多对多表中查询 AND

sql - 从最后插入的行中选择 id

mysql - 对于已知的其他几列,选择具有 MAX(列) 的一行,无需子查询

sql - .sql 文件的存储过程

php - 将一个查询的结果传递到另一个查询中

MySQL 查询给出无效结果

sql - 拆分 SQL Server 2005 表中的数字和字母

mysql - Symfony4 - 计数查询的 Doctrine 分页性能低(634484 条记录)

sql - 当列值为 null 时,不要在 where 条件中附加 "and"子句

SQL:多个嵌套聚合函数