Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL recursive query that gets all ancestors of an item

Tags:

sql

sql-server

ID       parent_id   name --------------------- 1        2            first  2        4            second 3        3            third 4        5            fourth 5        -           fifth 

Ancestors list of first should be (2, 4, 5)

like image 823
Kld Avatar asked May 25 '13 11:05

Kld


People also ask

How do you write a recursive query in SQL?

Recursion is achieved by WITH statement, in SQL jargon called Common Table Expression (CTE). It allows to name the result and reference it within other queries sometime later. Here is a sample. Query (SELECT 1 AS n) now have a name — R .

How do I create a hierarchical recursive query in MySQL?

MySQL 8+ with recursive cte (id, name, parent_id) as ( select id, name, parent_id from products where parent_id = 19 union all select p.id, p.name, p. parent_id from products p inner join cte on p.


2 Answers

with name_tree as (    select id, parent_id, name    from the_unknown_table    where id = 1 -- this is the starting point you want in your recursion    union all    select c.id, c.parent_id, c.name    from the_unknown_table c      join name_tree p on p.parent_id = c.id  -- this is the recursion )  select * from name_tree where id <> 1; -- exclude the starting point from the overall result 

SQLFiddle: http://sqlfiddle.com/#!3/87d0c/1

like image 100
a_horse_with_no_name Avatar answered Sep 20 '22 22:09

a_horse_with_no_name


You can use something like this:

with parents as  (   select ID, parent_ID   from t   where parent_ID is not null   union all    select p.ID, t.parent_ID   from parents p     inner join t on p.parent_ID = t.ID       and t.parent_ID is not null       and t.ID <> t.parent_ID ) select *   , parents = '(' + stuff     (       (         select ', ' + cast(p.parent_ID as varchar(100))         from parents p          where t.ID = p.ID         for xml path('')       ), 1, 2, ''     ) + ')' from t order by ID 

SQL Fiddle with demo.

This combines two very common T-SQL techniques - using a CTE to get a hierarchy and using FOR XML PATH to get a CSV list.

like image 40
Ian Preston Avatar answered Sep 22 '22 22:09

Ian Preston