2

我有一个表,其中包含一个键字段、一个后续键和最多两个先前的键。如何创建基于等于以下键的下一条记录排序的结果?

KEY,PRKEY1,PRKEY2,FLWKEY   
-------------------------------
3701401,0000000,0000000,3701403
3701403,3701401,0000000,3701421
3701402,0000000,0000000,3701404
3701404,3701402,0000000,3701421
3701421,3701404,3701403,3701405
3701405,3701421,0000000,3701423
3701299,0000000,0000000,3701210
3701210,3701299,0000000,3702007
3702007,3701210,0000000,3701005
3701005,3702007,0000000,3701423
3701423,3701405,3701005,3701411
3701413,0000000,0000000,3701411
3701411,3701423,3701413,3701431
3701431,3701411,3701005,3701455
3701451,0000000,0000000,3701455
3701455,3701431,3701451,3701443
3701443,3701455,0000000,3701445
3701445,3701443,0000000,3701432
3701432,3701445,0000000,3701434
3701434,3701432,0000000,3701435
3701435,3701434,0000000,0000000

结果应如下所示:

KEY,PRKEY1,PRKEY2,FLWKEY
-------------------------------    
3701401,0000000,0000000,3701403
3701403,3701401,0000000,3701421
3701421,3701404,3701403,3701405
3701405,3701421,0000000,3701423
3701423,3701405,3701005,3701411
3701411,3701423,3701413,3701431
3701431,3701411,3701005,3701455
3701455,3701431,3701451,3701443
3701443,3701455,0000000,3701445
3701445,3701443,0000000,3701432
3701432,3701445,0000000,3701434
3701434,3701432,0000000,3701435
3701435,3701434,0000000,0000000

提前致谢。我只有大约 50k 条记录可以通过这种方式进行整理。

4

1 回答 1

3
WITH    q (key, prkey1, prkey2, flwkey, init, lvl) AS
        (
        SELECT  *, key, 1
        FROM    mytable
        WHERE   key = 3701401
        UNION ALL
        SELECT  mt.*, q.init, q.lvl + 1
        FROM    q
        JOIN    mytable mt
        ON      mt.key = q.flwkey
        )
SELECT  key, prkey1, prkey2, flwkey
FROM    q
ORDER BY
        init, lvl

这是一个链表,您需要在递归 CTE 中遍历它。

sqlfiddle在这里

于 2012-11-14T21:42:11.670 回答