Known as one of the most popular open source database, MySQL is widely used in various scenarios, ApsaraDB RDS for MySQL of Alibaba Cloud provided critical relief for companies, especially small and medium-sized enterprises affected by novel coronavirus (COVID-19).
In SQL Server, it is easy to use a CTE expression to make an infinite hierarchy of parent-child relationship queries, and in versions that do not support CTE expressions, it is easy to do so with recursive functions.
In MySQL, this instance of the requirement is slightly more complicated, there is no recursive query in MySQL, no table-valued function, function does not support recursion, so it is usually implemented by loop, it seems awkward. Today see a single statement to implement the recursive query, ideas unique, share.
Table structure and data
CREATE TABLE table1(id int, name varchar(10), parent_id int);
INSERT table1 VALUES
(1, ‘Home’, 0),
(2, ‘About’, 1),
(3, ‘Contact’, 1),
(4, ‘Legal’, 2),
(5, ‘Privacy’, 4),
(6, ‘Products’, 1),
(7, ‘Support’, 2);
Query id = 5 for all parents
SELECT ID.level, DATA.* FROM(
SELECT
@id as _id,
( SELECT @id := parent_id
FROM table1
WHERE id = @id
) as _pid,
@l := @l+1 as level
FROM table1,
(SELECT @id := 5, @l := 0 ) b
WHERE @id > 0
) ID, table1 DATA
WHERE ID._id = DATA.id
ORDER BY level;
According to this parent query method, it is easy to write down all children of the following query id=2 all children
SELECT ID.level, DATA.* FROM(
SELECT
@ids as _ids,
( SELECT @ids := GROUP_CONCAT(id)
FROM table1
WHERE FIND_IN_SET(parent_id, @ids)
) as cids,
@l := @l+1 as level
FROM table1,
(SELECT @ids :=’1’, @l := 0 ) b
WHERE @ids IS NOT NULL
) id, table1 DATA
WHERE FIND_IN_SET(DATA.id, ID._ids)
ORDER BY level, id
This article explains how to make a sentence in MySQL to achieve an infinite level of parent-child relationship query, more relevant content please focus on PHP Chinese web.