[英]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.