[英]Convert OUTER APPLY to LEFT JOIN
We have query which is slow in production(for some internal reason),我们有生产缓慢的查询(由于某些内部原因),
SELECT T2.Date
FROM Table1 T1
OUTER APPLY
(
SELECT TOP 1 T2.[DATE]
FROM Table2 T2
WHERE T1.Col1 = T2.Col1
AND T1.Col2 = T2.Col2
ORDER BY T2.[Date] DESC
) T2
But when I convert to LEFT JOIN it become fast,但是当我转换为 LEFT JOIN 时,它变得很快,
SELECT Max(T2.[Date])
FROM Table1 T1
LEFT JOIN Table2 T2
ON T1.Col1 = T2.Col1
AND T1.Col2 = T2.Col2
GROUP BY T1.Col1, T1.Col2
Can we say that both queries are equal?我们可以说两个查询是相等的吗? If not then how to convert it properly.如果不是,那么如何正确转换它。
The queries are not exactly the same.查询并不完全相同。 It is important to understand the differences.了解这些差异很重要。
If t1.col1
/ t1.col2
are duplicated, then the first query returns a separate row for each duplication.如果t1.col1
/ t1.col2
重复,则第一个查询为每个重复返回单独的行。 The second combines them into a single row.第二个将它们组合成一行。
If either t1.col1
or t1.col2
are NULL
, then the first query will return NULL
for the maximum date.如果t1.col1
或t1.col2
为NULL
,则第一个查询将返回NULL
的最大日期。 The second will return a row and the appropriate maximum.第二个将返回一行和适当的最大值。
That said, the two queries should have similar performance, particularly if you have an index on table2(col1, col2, date)
.也就是说,这两个查询应该具有相似的性能,特别是如果您在table2(col1, col2, date)
上有索引。 I should note that under some circumstances the apply
method is faster than join
s, so relative performance depends on circumstances.我应该注意到在某些情况下apply
方法比join
更快,因此相对性能取决于情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.