MySQL Recursive从父级获取所有子级 [英] MySQL Recursive get all child from parent

查看:178
本文介绍了MySQL Recursive从父级获取所有子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,我在Mysql上使用递归查询在一个表上查找lv 2和lv3子级...
我正在使用的数据库结构:

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

我期望的结果,当过滤数据时,id = 1,它将生成我期望的结果.

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

或者这是插图.

我到处都看过,并且阅读了 http://mikehillyer .com/articles/managing-hierarchical-data-in-mysql/,但是我没有找到想要的结果.
感谢您的任何帮助

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

推荐答案

SELECT *
FROM TABLENAME
WHERE PARENT = 1
UNION
SELECT * 
FROM TABLENAME
WHERE PARENT IN 
    (SELECT ID FROM TABLENAME WHERE PARENT = 1)

这篇关于MySQL Recursive从父级获取所有子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆