简体   繁体   English

Join是否等效于带有子查询列的查询?

[英]Is a Join equivalent to a query with a subquery for a column?

Sorry for the newbie sql questions but isn't this the same thing: 对不起,新手SQL问题,但不是同一回事:

select a.productid, sum(b.qty)
from table1 a
inner join table2 b on b.productid = a.productid
group by a.productid
;

select a.productid
,(select sum(b.qty) from table2 b where b.productid = a.productid)
from table1 a
group by a.productid
;

Why would anyone ever use a query like above in the select, is this some old school thing to forget about using or should I still consider using it for some possible future problems? 为什么有人会在选择中使用上面的查询,这是一些老派的事情要忘记使用,还是我应该考虑将其用于将来可能出现的一些问题?

No, they are not in fact the same thing. 不,它们实际上不是一回事。 There are multiple differences, but the most obvious is that the join will filter out any unmatching rows. 有多种差异,但最明显的就是join将筛选出任何不匹配的行。 The correlated subquery will return all rows in the first table. 相关子查询将返回第一个表中的所有行。

There are other differences as well. 也有其他差异。 The sum() s will not be the same if there are duplicate productid s in the first table. 如果第一个表中有重复的productidsum()将会不同。 The execution plans are going to be different (because the result sets are different). 执行计划将有所不同(因为结果集不同)。 Under some circumstances, the correlated subquery will be faster. 在某些情况下,相关的子查询会更快。

More generally, there are situations where the correlated subquery is the simplest way to express logic. 更一般地,在某些情况下,相关子查询是表达逻辑的最简单方法。 And, as mentioned above, it can also produce the fastest execution plan under some circumstances. 并且,如上所述,在某些情况下,它还可以产生最快的执行计划。

First query: 第一个查询:

select a.productid, sum(b.qty)
from table1 a
inner join table2 b on b.productid = a.productid
group by a.productid

It won't return row if there is no corresponding value in table2. 如果table2中没有相应的值,则不会返回row。

Second query is like LEFT JOIN : 第二个查询就像LEFT JOIN

select a.productid
,(select sum(b.qty) from table2 b where b.productid = a.productid)
from table1 a
group by a.productid
<=>
select a.productid, sum(b.qty)
from table1 a
left join table2 b on b.productid = a.productid
group by a.productid

Keep performance in mind... inner join is much faster than subselect. 注意性能...内部联接比子选择要快得多。 A subselect loops through all matching results, so complexity is N x M... causing poor performance. 子选择遍历所有匹配结果,因此复杂度为N x M ...导致性能不佳。 Joins have a better performance in most cases. 在大多数情况下,联接具有更好的性能。

See https://www.essentialsql.com/subquery-versus-inner-join/ 参见https://www.essentialsql.com/subquery-versus-inner-join/

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

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