I need help with a recursive query. Assuming the following table:
CREATE TEMPORARY TABLE tree (
id integer PRIMARY KEY,
parent_id integer NOT NULL,
name varchar(50)
);
INSERT INTO tree (id, parent_id, name) VALUES (3, 0, 'Peter'), (2,0, 'Thomas'), (5,2, 'David'), (1, 0, 'Rob'), (8, 0, 'Brian');
I can retrieve a list of all people and their children with the following query:
WITH RECURSIVE recursetree(id, parent_id) AS (
SELECT id, parent_id FROM tree WHERE parent_id = 0
UNION
SELECT t.id, t.parent_id
FROM tree t
JOIN recursetree rt ON rt.id = t.parent_id
)
SELECT * FROM recursetree;
How can I list them in order, and also sort the first level items by name? For example, the desired output would be:
id, parent_id, name
8, 0, "Brian"
3, 0, "Peter"
1, 0; "Rob"
2, 0, "Thomas"
5, 2, " David"
Thanks,
**EDIT. Please note that adding an ORDER BY won't work: **
WITH RECURSIVE recursetree(id, parent_id, path, name) AS (
SELECT
id,
parent_id,
array[id] AS path,
name
FROM tree WHERE parent_id = 0
UNION ALL
SELECT t.id, t.parent_id, rt.path || t.id, t.name
FROM tree t
JOIN recursetree rt ON rt.id = t.parent_id
)
SELECT * FROM recursetree ORDER BY path;
The above will retain the parent child relationship (children follow their parents), but applying any other ORDER BY clause (ie: name - like some have suggested) will cause the result to lose it's parent-child relationships.
See also this (translated) article about CTE's in PostgreSQL: wiki.phpfreakz.nl
Edit: Try this one, using an array:
WITH RECURSIVE recursetree(id, parent_ids, firstname) AS (
SELECT id, NULL::int[] || parent_id, name FROM tree WHERE parent_id = 0
UNION ALL
SELECT
t.id,
rt.parent_ids || t.parent_id,
name
FROM tree t
JOIN recursetree rt ON rt.id = t.parent_id
)
SELECT * FROM recursetree ORDER BY parent_ids;
You can add a path to your query and order by it at the end:
WITH RECURSIVE recursetree(id, parent_id,path) AS (
SELECT id, parent_id,id||'' as path FROM tree WHERE parent_id = 0
UNION
SELECT t.id, t.parent_id,concat(rt.path,'_',t.id)
FROM tree t
JOIN recursetree rt ON rt.id = t.parent_id
)
SELECT * FROM recursetree
ORDER BY rt.path;
Related
My question is how to add the values I-95 as it related to I-300
and I-390 as it relate to I-20 to IO_RELATED output
The sample data is:
CREATE TABLE TBL_IORELATE (ID, MainID, RelatedID) AS
SELECT 1, 'I-225', 'I-20' FROM DUAL UNION ALL
SELECT 2, 'I-225', 'I-35' FROM DUAL UNION ALL
SELECT 3, 'I-225', 'I-300' FROM DUAL UNION ALL
SELECT 4, 'I-410', 'I-20' FROM DUAL UNION ALL
SELECT 5, 'I-410', 'I-50' FROM DUAL UNION ALL
SELECT 6, 'I-300', 'I-95' FROM DUAL UNION ALL
SELECT 7, 'I-455', 'I-300' FROM DUAL UNION ALL
SELECT 8, 'I-20', 'I-390' FROM DUAL;
The query I want to adapt from my previous question is:
SELECT id,
LISTAGG(value, ',') WITHIN GROUP (ORDER BY value) AS io_related
FROM (
SELECT DISTINCT id, value
FROM (
SELECT CONNECT_BY_ROOT MainID AS id,
MainID,
RelatedID
FROM TBL_IORELATE
START WITH MainID IN ('I-225')
CONNECT BY NOCYCLE
PRIOR MainID = MainID
OR PRIOR RelatedID = RelatedID
)
UNPIVOT(value FOR key IN (MainID, RelatedID))
WHERE id <> value
)
GROUP BY id
db<>fiddle here
Connect to any mainid to itself or relatedid and vice versa:
SELECT id,
LISTAGG(value, ',') WITHIN GROUP (ORDER BY value) AS io_related
FROM (
SELECT DISTINCT id, value
FROM (
SELECT CONNECT_BY_ROOT MainID AS id,
MainID,
RelatedID
FROM TBL_IORELATE
START WITH MainID IN ('I-225')
CONNECT BY NOCYCLE
PRIOR MainID IN (RelatedID, MainID)
OR PRIOR RelatedID IN (RelatedID, MainID)
)
UNPIVOT(value FOR key IN (MainID, RelatedID))
WHERE id <> value
)
GROUP BY id
Which outputs:
ID
IO_RELATED
I-225
I-20,I-300,I-35,I-390,I-410,I-455,I-50,I-95
db<>fiddle here
My first query returns the first 10 message ids:
SELECT * from message WHERE $1 IN (creator_id, recipient_id)
AND parent_id is null
ORDER BY date_posted
DESC FETCH FIRST 10 ROW ONLY
[1, 2, 4, 6, 10, 14, 17, 18, 19, 23]
Using each message_id, my second query gets the message_id with the MAX value of each of their Linear trees:
With RECURSIVE recursetree AS
(
SELECT * FROM message WHERE message_id = $1
UNION ALL
SELECT t.*
From message t
JOIN recursetree rt ON rt.message_id = t.parent_id
)
SELECT * from recursetree where parent_id is not distinct
from (select max(parent_id) from recursetree)
Combining these two queries only gets one row which is the max value of the linear tree of the last message_id of 23. How would I get all rows?
with RECURSIVE cte as
(
(
SELECT * from message WHERE $1 IN (creator_id, recipient_id)
AND parent_id is null ORDER BY date_posted DESC
FETCH FIRST 10 ROW ONLY
)
UNION
SELECT t.*
From message t
JOIN cte rt ON rt.message_id = t.parent_id
)
SELECT * FROM cte where parent_id is not distinct
from (select max(parent_id) from cte)
If you want to get the last message of each,
I think you should extract data without children.
select m.*
from message m
left join message child on m.message_id = child.parent_id
where child.message_id is null
Suppose my data in table like in attached picture without having path column.
i want to generate a column, like "Path" in picture using traverse CTE in sql
Picture example:
Use a recursive CTE to solve this:
WITH recCTE
AS (
SELECT id,
parentid,
id AS original_id,
parentid AS original_parentid,
name as original_name,
1 AS depth,
CAST(name AS VARCHAR(5000)) AS path
FROM yourtable
UNION ALL
SELECT yourtable.id,
yourtable.parentid,
recCTE.original_id,
recCTE.original_parentID,
recCTE.original_name,
recCTE.depth + 1,
CAST(recCTE.path + '-' + yourtable.name as VARCHAR(5000))
FROM recCTE
INNER JOIN yourtable
ON recCTE.parentid = yourtable.id
WHERE depth < 20 /*prevent cycling*/
)
SELECT original_id as id, original_parentid as parentid, original_name as name, depth, path
FROM recCTE t1
WHERE depth = (SELECT max(depth) FROM recCTE WHERE t1.original_id = recCTE.original_id)
sqlfiddle example
That CTE has two parts:
The "Anchor Member" which is the first selection from the table. This defines the output (which columns and column type are in the output).
The "Recursive Member" which selects from the CTE in which it's contained at is performed iteratively until the join fails.
In this example we capture the path by concatenating the path to the name over and over again in the recursive member. We also track Depth (how many recursions have been performed) and track the current id and parentid as well as the original id and original parentid so they can be selected in the final SELECT statement.
try this,
;with cte(id,parentId,name,path,cnt)
AS
(
select id,parentid,name,cast(name as VARCHAR(1024)) as path, 1 as cnt from test_cte
union all
select a.id,a.parentid,a.name,CAST((a.name + '-' +path ) as VARCHAR(1024)), case when a.parentid is null then 0 else cnt + 1 end as cnt from test_cte a join cte c on c.id = a.parentid where c.cnt is not null
)
select id,parentid,name,path from (select id,parentid,name,path, row_number() over(partition by id order by cnt desc) as rank from cte) a where a.rank = 1 order by 1 asc ;
here is the simplified table
filesystem (id, name, parentId);
and some entries
(1, 'root', NULL)
(2, 'folder', 1)
(3, 'subfolder', 2)
(4, 'subsubfolder', 3)
is there a way using native SQL to print the absolute path of one entry ?
for instance, the last entry would print 'root/folder/subfolder/subsubfolder'. the entry 2 would print 'root/folder' and so on.
You can do something like this
with tree(id, Level, Hierarchy) as
(
select id, 0, cast(Name as varchar(max))
from filesystem
union all
select a.id, b.Level+1,
b.Hierarchy+'/'+a.Name
from filesystem a
inner join tree b on a.parentid=b.id
)
select top(1) id, Hierarchy
from tree
where id=4
order by Level desc
It will give you id with full file path.
TO read in details you can check this
You didn't state your DBMS, the following is standard (ANSI) SQL:
with recursive folder_tree as (
select id, name, parentid, name as fullpath
from filesystem
where parentid is null
union all
select c.id, c.name, c.parentid, p.fullpath||'/'||c.name
from filesystem c
join folder_tree p on c.parentid = p.id
)
select *
from folder_tree
SQLFiddle: http://sqlfiddle.com/#!15/91332/7
Recursive CTE solution for SQL Server:
WITH FileSystem(id,name,parentID)
AS
(
SELECT 1,'root',NULL
UNION ALL
SELECT 2,'folder',1
UNION ALL
SELECT 3,'subFolder',2
UNION ALL
SELECT 4,'subSubFolder',3
),
CTE_Recursion
AS
(
SELECT ROW_NUMBER() OVER (ORDER BY ID) filePath_id,ID,CAST(name AS VARCHAR(100)) name,parentID
FROM FileSystem
WHERE parentID IS NULL
UNION ALL
SELECT A.filePath_id,B.id,CAST(A.name + '\' + B.name AS VARCHAR(100)),B.parentID
FROM CTE_Recursion A
INNER JOIN FileSystem B
ON A.ID = B.parentID
)
SELECT filePath_id,MAX(name) filePath
FROM CTE_Recursion
GROUP BY filepath_id
Results:
filePath_id filePath
-------------------- -----------------------------------
1 root\folder\subFolder\subSubFolder
I have table witch contains fields: id, parent_id, name (etc.)
i want to order this table in "tree travel order" ie.
id parent_id
1, 0
3, 1
5, 1
2, 0
8, 2
4, 0
9, 4
(...)
in short describe: take root node, append all children, take next root node append children etc.
By your description I assume you mean breadth-first order, which could be easly done using a WITH RECURSIVE query (PostgreSQL 8.4+):
WITH RECURSIVE tree
AS
(
SELECT
node_name, id, parent_id, NULL::varchar AS parent_name
FROM foo
WHERE parent_id IS NULL
UNION
SELECT
node_name, f1.id, f1.parent_id, tree.node_name AS parent_name
FROM
tree
JOIN foo f1 ON f1.parent_id = tree.id
)
SELECT node_name, empno, parent_id, node_name FROM tree;
You could also use depth-first order using the following SQL:
WITH RECURSIVE tree
AS
(
SELECT
node_name, id, parent_id, NULL::varchar AS parent_name, id::text AS path
FROM foo WHERE parent_id IS NULL
UNION
SELECT
node_name, f1.id, f1.parent_id, tree.node_name AS parent_name, tree.path || '-' || f1.id::text AS path
FROM
tree
JOIN foo f1 ON f1.parent_id = tree.id
)
SELECT node_name, empno, parent_id, node_name, path FROM tree ORDER BY path;
As noticed by synergetic, the solution for depth-first order provided by Diogo Biazus won't work for id's with different number of digits.
But you can use this solution instead, that uses arrays of integer :
WITH RECURSIVE tree
AS
(
SELECT
node_name, id, parent_id, NULL::varchar AS parent_name, array[id] AS path
FROM foo WHERE parent_id IS NULL
UNION
SELECT
node_name, f1.id, f1.parent_id, tree.node_name AS parent_name, tree.path || f1.id AS path
FROM
tree
JOIN foo f1 ON f1.parent_id = tree.id
)
SELECT node_name, empno, parent_id, node_name, path FROM tree ORDER BY path;
You can also use the excellent LTree module, but you need to reorganise your data a bit.
SELECT * FROM table ORDER BY id,parent_id
That should order my columns in the order there placed within the query.
Unless you mean GROUP the items, witch I think you do, then use
SELECT * FROM table ORDER BY id GROUP BY parent_id
And i also advise you to read this article: http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/