Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 先运行哪一个:joins还是where子句_Sql_Sql Server 2008 - Fatal编程技术网

Sql 先运行哪一个:joins还是where子句

Sql 先运行哪一个:joins还是where子句,sql,sql-server-2008,Sql,Sql Server 2008,我有一个查询,其中我使用了13个左外部联接。非常左的表有大量数据,因此执行查询和返回结果需要花费很多时间。 但是,当我使用where子句来过滤结果时,所花费的时间非常少。 现在我不知道是哪一个先执行:产生结果的连接,然后where子句从中过滤,还是先过滤结果,然后获取结果的连接。通常,任何DBMS(如SQL)都会进行自己的查询优化,使用它认为最快的算法。所以它是过滤,然后加入。阅读: 及 我正在重读Pinal Dave的帖子,我发现了这个,它可能会帮助你理解 在子句上理解它是在联接之前应用

我有一个查询,其中我使用了13个左外部联接。非常左的表有大量数据,因此执行查询和返回结果需要花费很多时间。 但是,当我使用where子句来过滤结果时,所花费的时间非常少。 现在我不知道是哪一个先执行:产生结果的连接,然后where子句从中过滤,还是先过滤结果,然后获取结果的连接。

通常,任何DBMS(如SQL)都会进行自己的查询优化,使用它认为最快的算法。所以它是过滤,然后加入。

阅读:

我正在重读Pinal Dave的帖子,我发现了这个,它可能会帮助你理解

在子句上理解它是在联接之前应用的,这就是为什么它检索Table2的所有结果,其中有Flag=1,但它不影响Table1,所以它检索Table1的所有行。当应用WHERE子句时,它将应用于完整结果,因此它将删除表1和表2中标志不等于1的所有行,基本上保留表1和表2中的标志=1行。

对联接进行筛选,以防止在联接过程中添加行

select a.*,b.*
from   A a left join B b 
on     a.id =b.id and a.id=2;

id          id
----------- -----------
1           NULL
2           2
3           NULL
连接发生后,将在何处进行筛选

select a.*,b.* 
from   A a left join B b 
on     a.id =b.id 
where  a.id=2;

id          id
----------- -----------
2           2

请记住,无论SQL Server的查询优化器选择如何调整您的步骤,您所能做的最好的事情是正确维护和索引您的数据,以便服务器可以更轻松地完成其工作。维护良好的
统计信息也有帮助。如果您获得了所需信息,请不要忘记更新投票并将其标记为已接受
select a.*,b.* 
from   A a left join B b 
on     a.id =b.id 
where  a.id=2;

id          id
----------- -----------
2           2