简体   繁体   English

自我加入的替代方案

[英]An alternative to self-join

I have a table that has a reference to itself like this: 我有一个像这样引用自己的表:

Id   Total   Prev   Session
1  | 10    | NULL | 1
2  | 15    | 1    | 1
3  | 11    | NULL | 2
4  | 29    | 2    | 1
5  | 19    | 3    | 2
6  | 47    | 4    | 1

And I need to get the differences for the specific sessions. 我需要了解特定会话的差异。
Like this for session 1: 对于第1场会议,这样:

1. 10 -- None to 10
2. 5  -- 10 to 15
3. 14 -- 15 to 29
4. 18 -- 29 to 47

To do this, I use: 为此,我使用:

SELECT  F.Total - P.Total AS Difference
FROM    Foo F LEFT OUTER JOIN
        Foo P ON F.Prev = P.Id
WHERE   Session = @Session

Which is extremely slow. 这是非常缓慢的。
How can I retrieve these differences faster without altering the table? 如何在不更改表格的情况下更快地检索这些差异?

You cannot. 你不能。 This is the fastest query possible, although it may become a lot faster if you add an index on Session , Prev and Id . 这是可能的最快查询,但如果在SessionPrevId上添加索引可能会快得多。

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

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