MySQL sql statement to query all parent node information of child nodes

In SQL Server, it is easy to use CTE expressions to achieve unlimited levels of parent-child relationship queries; in versions that do not support CTE expressions, it can also be easily achieved with the help of function recursion.
In MySQL, the example of this requirement is slightly more complicated. MySQL does not support recursive query, no table-valued function, and function does not support recursion, so it is usually implemented with loops, which is rather awkward. Today I saw a recursive query implemented with a single statement. The idea is unique. Share it.

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 all parents with id = 5

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;

根据这个父级查询方法,很容易可以写出查所有子级的,下面的查询 id=2 的所有子级

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

According to this parent query method, it is easy to write to check all children, 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

Guess you like

Origin blog.csdn.net/dndndnnffj/article/details/111230511