查询选择下一个id顺序

ss2ws0br  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(287)

我有一张表,上面有id和nextid,如下所示:

MainID  ||  NextID
1       ||  2
2       ||  3
3       ||  5
4       ||  6
5       ||  4
6       ||  ...
...     ||  ...

我想要实现的是像这样选择数据

MainID  ||  NextID
1       ||  2
2       ||  3
3       ||  5
5       ||  4
4       ||  6
6       ||  ...
...     ||  ...

我尝试的是简单的查询,比如:

SELECT * FROM 'table' ORDER BY NextID

但它当然不能满足我的需要,我有一个想法,创建一个临时表和插入与循环,但需要太多的时间来完成:

WHILE @NextID IS NOT NULL
BEGIN
    INSERT INTO 'table'(MainID, NextID)
    SELECT MainID, NextId
    FROM 'table' WHERE MainID=@NextID

END

有人能帮我吗?
谢谢

dfddblmv

dfddblmv1#

对于这种特殊情况,您可以使用右连接进行排序

select t2.*
  from some_table t1
 right join some_table t2
    on t1. main_id = t2.next_id
 order by case when t2.next_id is null then 9999999 else t2.main_id + t2.next_id end;

“order by”部分中的999999将把最后一行(6,null)放在输出的末尾。
祝您在对真实数据采用查询时好运

rt4zxlrg

rt4zxlrg2#

递归cte将按访问节点的顺序返回行

with t as (
  select f.*, right('00000000'+cast(f.mainId as varchar(max)),9) path
  from yourtable f
  where MainID=1
  union all
  select f.*, path + '->' + right('00000000'+cast(f.mainId as varchar(max)),9)
  from t
  join yourtable f on t.NextID = f.MainID
)
select * 
from t
order by path

db<>小提琴 where MainId=1 是一个任意的开始。你也可以从 where not exists (select 1 from yourtable f2 where f2.Nextid = f.MainId) 编辑
添加显式 order by

相关问题