简体   繁体   English

SQL Server表或子查询是否可以联接?

[英]SQL Server table or subquery for join?

I'm now using a rather cryptic DB (SAP) running on SQL server 2012, only SELECT permission, so some things are difficult to debug/optimize. 我现在使用的是运行在SQL Server 2012上的相当隐秘的数据库(SAP),只有SELECT权限,因此有些事情很难调试/优化。

I have a big table 'table1', and smaller tables 'table2', 'table3'. 我有一个大表'table1'和一个小表'table2','table3'。 The big table with millions of rows will be filtered to 100 rows at most in the "where" statement 包含数百万行的大表将在“ where”语句中最多过滤为100行

I have to start from table1. 我必须从表1开始。 Would you recommend: 您会建议:

select fields 
from table1
left join table2 
left join table3
where table1.field1 = 'x' 
  and table1.field2 = 'y'

Or 要么

Select 
    fields 
from
    (select fields 
     from table1 
     where table1.field1 = 'x' and table1.field2 = 'y') as t1
left join
    table2
left join
    table3

And, why? 而且,为什么呢? I want to understand this a little better. 我想更好地理解这一点。

Thank you! 谢谢!

Ideally 理想的情况下

select fields 
from table1
left join table2
left join table3
where table1.field1 = 'x' and table1.field2 = 'y'

This code will first join all the tables and then apply the filter mentioned in the where condition. 此代码将首先连接所有表,然后应用where条件中提到的过滤器。

Select fields 
from
     (select fields 
      from table1 
      where table1.field1 = 'x' and table1.field2 = 'y') as t1
left join table2
left join table3

Whereas this code will first of all filter the table based on the filter criteria, load it in a temporary location and only then join the filtered rows to the other tables. 而此代码将首先根据过滤条件过滤表,将其加载到临时位置,然后才将过滤后的行连接到其他表。

If table1 has a lot of rows with very few rows satisfying the filter condition (Low Cardinality) the 2nd code would run faster. 如果table1的行很多,但满足筛选条件(低基数)的行很少,那么第二个代码将运行得更快。

If the filter does not reduce the number of rows much then the bottleneck would be the loading into the temporary space in code 2 due to which code 1 might be better 如果过滤器没有减少行数,那么瓶颈将是代码2中临时空间的加载,因此代码1可能更好

NOTE: : This answer would change based on your SQL engine and query optimizer. 注意::此答案将根据您的SQL引擎和查询优化器而改变。 Many optimizers are smart enough to detect that in code 1 only filtered rows need to be joined so in that case code1 would be better 许多优化器非常聪明,足以检测到在代码1中仅需要将过滤后的行进行连接,因此在这种情况下,代码1会更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM