问题
i have this case using recursive query on Mysql to find lv 2 and lv3 child on one table...
database structure i'm using:
id name parent
1 A 0
2 B 0
3 C 0
4 D 1
5 E 1
6 F 2
7 G 2
8 H 3
9 I 3
10 J 4
11 K 4
The result i was expecting, when filtering the data, where id=1, it will generate the result i'm expecting.
id name parent
4 D 1
5 E 1
10 J 4
11 K 4
or this is the illustration.
i've been looking everywhere, and reading this http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/, but i didn't find the result i was looking for..
any help would be appreciated, thanks
回答1:
SELECT *
FROM TABLENAME
WHERE PARENT = 1
UNION
SELECT *
FROM TABLENAME
WHERE PARENT IN
(SELECT ID FROM TABLENAME WHERE PARENT = 1)
回答2:
if you want to get all level child of a particular parent then you should try this
select id,
name,
parent
from (select * from tablename
order by parent, id) tablename,
(select @pv := '1') initialisation
where find_in_set(parent, @pv) > 0
and @pv := concat(@pv, ',', id)
回答3:
Try this, Much faster
SELECT * FROM table AS T1 INNER JOIN (SELECT id FROM table WHERE parent = 1) AS T2 ON T2.id = T1.parent OR T1.parent = 1 GROUP BY T1.id
来源:https://stackoverflow.com/questions/41913460/mysql-recursive-get-all-child-from-parent