HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Get the highest parent id recursively in MySQL

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
theparentrecursivelymysqlgethighest

Problem

I want to find the uppermost parent ID for each entry. For example,

CREATE TABLE t1
(
ID int(11) unsigned NOT NULL,
ParentID int(11) unsigned,
PRIMARY KEY (ID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;

INSERT INTO t1 (ID,ParentID) VALUES (1,NULL),(2,1),(3,2),(4,3);


I intent to get

ID     Highest ParentID
1      NULL
2      1
3      1
4      1


I planned to create a recursive query (MySQL 8 or MariaDB 10.5) by adding a condition to break the recursive when Parent ID is a specific value (e.g., NULL in the above case). I started with

WITH RECURSIVE cte (ID, ParentID) as (
  SELECT ID,ParentID FROM t1
  UNION ALL
  SELECT t2.ID,t2.ParentID FROM t1 t2
  INNER JOIN cte on t2.ParentID = cte.ID
)
SELECT * FROM cte;


but it does not work as I intend, as it gets the next ParentID instead of recursively.

Sample fiddle.

Solution

WITH RECURSIVE
cte as ( SELECT id, id nextid, parentid
FROM t1
UNION ALL
SELECT cte.id, t1.id, t1.parentid
FROM t1
JOIN cte ON cte.parentid = t1.id )
SELECT Id, nextid RootId
FROM cte
WHERE parentid IS NULL


https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=209df940143d3e984d418e49929bd847

Context

StackExchange Database Administrators Q#291321, answer score: 6

Revisions (0)

No revisions yet.