问题描述
可能的重复:
SQL WHERE 子句是否短路评估? >
我有以下关于此查询的问题:
I have the following question regarding this query:
select * from sometable
where 1=1 or (select count(*) from table2 > 0)
如果第一个条件为真(1=1
),SQL Server 还会做内部选择吗?还是在第一个条件为真时停止(如 C)
If the first condition is true (1=1
), does SQL Server still do the inner select?Or does it stop when the first condition is true (like C)
推荐答案
当 (1=1) 为真时停止.您可以使用 Ctrl-M 和 Ctrl-E 轻松检查
It stops when the (1=1) is true. You can check easily using Ctrl-M then Ctrl-E
考虑这个查询
select * from master..spt_values
where 1=1 or (select count(*) from master..sysobjects) > 0
执行计划仅显示 master..spt_values
中的扫描,而 sysobjects
中没有活动.
The execution plan only shows a scan in master..spt_values
and no activity in sysobjects
.
与 C 不同,它不会在 LEFTMOST 条件为真时停止,而是查询优化器独立于呈现的顺序计算,这是评估成本最低的.在常量 1 vs 1
的情况下,赢家很明显.
Contrary to C, it does not stop when the LEFTMOST condition is true, instead the query optimizer works out independently of order presented which is the least cost to evaluate. In the case of the constants 1 vs 1
the winner is clear.
这篇关于SQL Server 性能提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!