[英]How can I create “recursive sql”
我想做“链接”
例如,我有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}”,我想使用“限制10”
帮我!
我没有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;
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功能) )。
这适用于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)
其他答案清楚地证明了递归问题 - 实现在RDBMS供应商之间是不一致的。
或者,您可以使用“嵌套集”模型,它可以完全避免递归,并且应该很容易在与平台无关的SQL实现中构建。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.