Quantcast
Viewing all articles
Browse latest Browse all 207

CTE get all descendants with parents

Schema:

CREATE TABLE item (    id        int primary key,    parent_id int,    FOREIGN KEY(parent_id) REFERENCES item(id));INSERT INTO item    (id, parent_id)VALUES    (1, NULL),    (2, 1),    (3, 1),    (4, 2),    (5, 3),    (6, 3),    (7, 6);

Query:

WITH RECURSIVE descendants(id, parent_id) AS (    SELECT 1, parent_id FROM item        UNION ALL    SELECT item.id, descendants.parent_id    FROM item, descendants    WHERE item.parent_id=descendants.id)SELECT * FROM descendants;

Fiddle: http://sqlfiddle.com/#!5/27c03/4

Goal: given some parents (eg 2, 3) get all of its descendants.

I came up with the following CTE, but it returns far too many items.

SELECT * FROM descendants WHERE parent_id IN (2, 3);

Should give

id | parent_id4  | 25  | 36  | 37  | 3

The answer here is close, but my schema varies: https://dba.stackexchange.com/a/94944/253249


Viewing all articles
Browse latest Browse all 207

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>