根据指向同一个表的字段排序查询

时间:2009-08-26 19:18:49

标签: sql-server database linq tsql

我有一个名为“Sentence”的表格,其中包含以下字段:

ID         <--- OK
NextID     <--- FK To ID
Text

所以,如果我有以下记录:

*ID*            *NextID*          *Text*
1               12                The quick
3               40                jumps over
5               null              lazy dog.
12              3                 brown fox
40              5                 the

如果我知道序列的开头是ID = 1的记录,是否有办法根据NextID的顺序排序查询。与上面的例子一样,预期结果应该是......

The quick
brown fox
jumps over
the
lazy dog.

我正在寻找一个T-SQL语句,或者以某种方式使用Linq。提前谢谢!

3 个答案:

答案 0 :(得分:3)

试试这个:

declare @YourTable table (RowID int primary key, NextID int, TextValue varchar(50))

INSERT INTO @YourTable VALUES (1 , 12  ,'The quick')
INSERT INTO @YourTable VALUES (3 , 40  ,'jumps over')
INSERT INTO @YourTable VALUES (5 , null,'lazy dog.')
INSERT INTO @YourTable VALUES (12, 3   ,'brown fox')
INSERT INTO @YourTable VALUES (40, 5   ,'the')

;with cteview as (
SELECT * FROM @YourTable WHERE RowID=1
UNION ALL
SELECT y.* FROM @YourTable y
    INNER JOIN cteview   c ON y.RowID=c.NextID
) 
select * from cteview
OPTION (MAXRECURSION 9999) --go beyond default 100 levels of recursion to 9999 levels

输出:

RowID       NextID      TextValue
----------- ----------- --------------------------------------------------
1           12          The quick
12          3           brown fox
3           40          jumps over
40          5           the
5           NULL        lazy dog.

(5 row(s) affected)

答案 1 :(得分:0)

LINQ回答:

table.OrderBy(sentence => sentence.NextID);

编辑:我希望这次我能正确回答:

class Sentence
{
    public int Id;
    public int? NextId;
    public string Text;
    public Sentence(int id, int? nextId, string text)
    {
        this.Id = id;
        this.NextId = nextId;
        this.Text = text;
    }
}

var Sentences = new [] {
    new Sentence(1, 12, "This quick"),
    new Sentence(3, 40, "jumps over"),
    new Sentence(5, null, "lazy dog."),
    new Sentence(12, 3, "brown fox"),
    new Sentence(40, 5, "the"),
};

Func<int?, string> GenerateSentence = null;
GenerateSentence = (id) => id.HasValue? Sentences
    .Where(s => s.Id == id.Value)
    .Select(s => s.Text + " " + GenerateSentence(s.NextId))
    .Single() : string.Empty;

Console.WriteLine(GenerateSentence(1));

答案 2 :(得分:0)

如果您正在使用LINQ to SQL / Entities,那么生成的Sentence类应该具有您提到的所有属性,以及从外键引用下一句(让我们称之为NextSentence)的实体引用

然后你可以这样做:

Sentence s = Sentences.First();
StringBuilder sb = new StringBuilder();
do { sb.Append(s.Text); s = s.NextSentence; } while (s != null);

sb.ToString()会有你的答案。