gpt4 book ai didi

Sql Server - 外部应用与子查询

转载 作者:行者123 更新时间:2023-12-02 16:33:07 25 4
gpt4 key购买 nike

请考虑 Sql Server 中的以下 2 条语句:

这个使用嵌套子查询:

    WITH cte AS
(
SELECT TOP 100 PERCENT *
FROM Segments
ORDER BY InvoiceDetailID, SegmentID
)
SELECT *, ReturnDate =
(SELECT TOP 1 cte.DepartureInfo
FROM cte
WHERE seg.InvoiceDetailID = cte.InvoiceDetailID
AND cte.SegmentID > seg.SegmentID),
DepartureCityCode =
(SELECT TOP 1 cte.DepartureCityCode
FROM cte
WHERE seg.InvoiceDetailID = cte.InvoiceDetailID
AND cte.SegmentID > seg.SegmentID)
FROM Segments seg

这使用了 OUTER APPLY 运算符:

    WITH cte AS
(
SELECT TOP 100 PERCENT *
FROM Segments
ORDER BY InvoiceDetailID, SegmentID
)
SELECT seg.*, t.DepartureInfo AS ReturnDate, t.DepartureCityCode
FROM Segments seg OUTER APPLY (
SELECT TOP 1 cte.DepartureInfo, cte.DepartureCityCode
FROM cte
WHERE seg.InvoiceDetailID = cte.InvoiceDetailID
AND cte.SegmentID > seg.SegmentID
) t

考虑到两个 Segments 表可能有数百万行,这两个中哪一个可能会表现更好?

我的直觉是 OUTER APPLY 会表现得更好。

还有几个问题:

  1. 我对此非常确定,但仍然想确认在第一个解决方案中,CTE 实际上会执行两次(因为它被引用两次,并且 CTE 像宏一样内联扩展)。
  2. 在 OUTER APPLY 运算符中使用时,CTE 是否会为每行执行一次?当在第一个语句中的嵌套查询中使用时,它还会对每一行执行吗?

最佳答案

首先,去掉 CTE 中的前 100%。此处未使用 TOP,如果您希望对结果进行排序,则应在整个语句的末尾添加 Order By。其次,为了解决您关于性能的问题,如果被迫进行猜测,我的赌注将是第二种形式,因为它有一个子查询而不是两个。第三,您可以尝试的另一种形式是:

With RankedSegments As
(
Select S1.SegmentId, ...
, Row_Number() Over( Partition By S1.SegmentId Order By S2.SegmentId ) As Num
From Segments As S1
Left Join Segments As S2
On S2.InvoiceDetailId = S1.InvoiceDetailId
And S2.SegmentId > S1.SegmentID
)
Select ...
From RankedSegments
Where Num = 1

另一种可能性

With MinSegments As
(
Select S1.SegmentId, Min(S2.SegmentId) As MinSegmentId
From Segments As S1
Join Segments As S2
On S2.InvoiceDetailId = S1.InvoiceDetailId
And S2.SegmentId > S1.SegmentID
Group By S1.SegmentId
)
Select ...
From Segments As S1
Left Join (MinSegments As MS1
Join Segments As S2
On S2.SegmentId = MS1.MinSegmentId)
On MS1.SegmentId = S1.SegmentId

关于Sql Server - 外部应用与子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5434809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com