我想制作“链接”
例如,我有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以{id:“1”}开头?
select s.id, s.nextId from sample s
join sample ns on ns.id = s.nextId
它从第一个节点到全部。
我想开始“{some id}”,我想使用“limit 10”
帮助我!答案 0 :(得分: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;
答案 1 :(得分: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技术,是当今最先进的技术。
答案 2 :(得分: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)
答案 3 :(得分:0)
其他答案清楚地证明了递归问题 - RDBMS供应商的实现不一致。
或者,您可以使用"nested set"模型,它可以完全避免递归,并且应该很容易在与平台无关的SQL实现中构建。