数据库一个表有三个字段(id,name,fid)
id name fid
1 01 0
2 02 1
3 03 2
4 04 3
5 05 3
6 06 4
7 07 6
...............
现在怎么根据id查询下三级的内容
比如 查id=3的下三级子集 结果如下最好能不能把level级显示出来呢?
id name fid (level)
4 04 3 1
5 05 3 1
6 06 4 2
7 07 6 3
请问大家这种sql该怎么写呢
2 个解决方案
#1
mysql中没有cte写法,没法递归,很难受啊。。。
写个方法或存储过程之类的吧
http://blog.csdn.net/xiaodingdou/article/details/53286503?_t_t_t=0.9440201732795686
写个方法或存储过程之类的吧
http://blog.csdn.net/xiaodingdou/article/details/53286503?_t_t_t=0.9440201732795686
#2
明确层数的子级,可以用 对应层数的LEFT JOIN 搞定
SELECT DATA.*, ID.level
FROM tb DATA, (
SELECT A.id as A, B.id as B, C.id as C, D.id as D,
CASE
WHEN ISNULL(D.id) THEN 3
WHEN ISNULL(C.id) THEN 2
WHEN ISNULL(B.id) THEN 1
ELSE 0
END as level
FROM tb A
LEFT JOIN tb B ON B.fid = A.id
LEFT JOIN tb C ON C.fid = B.id
LEFT JOIN tb D ON D.fid = C.id
WHERE A.id = 3
) ID
WHERE DATA.id IN(ID.B, ID.C, ID.D);
#1
mysql中没有cte写法,没法递归,很难受啊。。。
写个方法或存储过程之类的吧
http://blog.csdn.net/xiaodingdou/article/details/53286503?_t_t_t=0.9440201732795686
写个方法或存储过程之类的吧
http://blog.csdn.net/xiaodingdou/article/details/53286503?_t_t_t=0.9440201732795686
#2
明确层数的子级,可以用 对应层数的LEFT JOIN 搞定
SELECT DATA.*, ID.level
FROM tb DATA, (
SELECT A.id as A, B.id as B, C.id as C, D.id as D,
CASE
WHEN ISNULL(D.id) THEN 3
WHEN ISNULL(C.id) THEN 2
WHEN ISNULL(B.id) THEN 1
ELSE 0
END as level
FROM tb A
LEFT JOIN tb B ON B.fid = A.id
LEFT JOIN tb C ON C.fid = B.id
LEFT JOIN tb D ON D.fid = C.id
WHERE A.id = 3
) ID
WHERE DATA.id IN(ID.B, ID.C, ID.D);