4

我想做“链接”

例如,我有 5 个帖子(id:“1”,id:“2”,id:“3”,id:“4”,id:“5”)

他们有一个序列

{id:"1", nextId:"2"},
{id:"2", nextId:"4"},
{id:"3", nextId:"0"},
{id:"4", nextId :"3"},
{id:"5", nextId:"0"},

当我从 "1" 搜索时,我得到一个结果:{id:"1"}, {id:"2"}, {id:"4"}, {id:"3"} 当我从 "5" 搜索时",我得到了一个结果:{id:"5"}

如何在 ANSI SQL 中找到 All start with {id:"1"}?

select s.id, s.nextId from sample s
join sample ns on ns.id = s.nextId

它从第一个节点到所有节点。

我想开始“{some id}”并且我想使用“limit 10”

帮我!

4

4 回答 4

2
create table links (id integer, nextid integer);

insert into links 
values 
(1, 2),
(2, 4),
(3, 0),
(4, 3),
(5, 0);

commit;

with recursive link_tree as (
   select id, nextid
   from links
   where id = 1  -- change this to change your starting node
   union all 
   select c.id, c.nextid
   from links c
     join link_tree p on p.nextid = c.id
)
select *
from link_tree;

这是 ANSI SQL,适用于 HSQLDB、PostgreSQL、H2、Firebird、DB2、Microsoft SQL Server、Oracle 11.2 和其他几个引擎——只是不适用于 MySQL(它不支持当今最先进的任何现代 SQL 特性)。

于 2012-10-18T09:48:23.973 回答
2

我没有 HSQLDB,但应该这样做:

WITH RECURSIVE chain(seq, me, next) AS (
  VALUES(0, CAST(null AS int), 1) -- start
  UNION ALL
  SELECT seq + 1, id, nextId
  FROM sample, chain
  WHERE id = next
)
SELECT * FROM chain WHERE seq > 0;
于 2012-10-18T09:27:58.310 回答
0

其他答案清楚地证明了递归的问题 - RDBMS 供应商的实现不一致。

或者,您可以使用“嵌套集”模型,它完全避免了递归,并且应该很容易在与平台无关的 SQL 实现中构建。

于 2012-10-18T10:23:48.993 回答
0

这适用于 sql server,也许它会在 HSQLDB 上帮助你

在您的示例中,如果您通知 1,它将返回

2->4->3->0

如果您想在开头添加 1 或者从结尾删除 0,这取决于您

CREATE table test_sequence(
id int,
next_id int
)

insert into test_sequence VALUES(1,2)
insert into test_sequence VALUES(2,4)
insert into test_sequence VALUES(3,0)
insert into test_sequence VALUES(4,3)
insert into test_sequence VALUES(5,0)



alter function selectSequence(@id int)
returns varchar(max)
begin
    declare @next varchar(max)
    select @next=next_id from test_sequence WHERE id =@id
    if (@next != '') begin
        return @next +'->'+ dbo.selectSequence(@next)
    end else begin
        select @next=''
    end
    return @next
end

select dbo.selectSequence(1)
于 2012-10-18T09:33:27.533 回答