简体   繁体   中英

How can I create “recursive sql”

I want to make "link"

for Example, I have a 5 posts (id: "1", id: "2", id: "3", id: "4", id: "5")

and they have a sequence

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

when I search from "1", I got a result : {id:"1"}, {id:"2"}, {id:"4"}, {id:"3"} when I search from "5", I got a result : {id:"5"}

How can I find All start with {id:"1"} in ANSI SQL?

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

It makes from first node to all.

I want to start "{some id}" and I want to use "limit 10"

help me!

I don't have HSQLDB but something like this should do it:

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;

This is ANSI SQL and works on HSQLDB, PostgreSQL, H2, Firebird, DB2, Microsoft SQL Server, Oracle 11.2 and several other engines - just not on MySQL (which does not support any of the modern SQL features which are state of the art nowadays).

this works on sql server, maybe it will help you on HSQLDB

on your example, if you inform 1, it would return

2->4->3->0

its up to you if you want to add the 1 in the begining or maybe remove the 0 from the end

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)

The problem with recursion is clearly demonstrated by the other answers - the implementation is inconsistent across RDBMS vendors.

Alternatively, you can use the "nested set" model, which avoids recursion altogether, and should be easy to construct in a platform-agnostic SQL implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM