如何让MySQL中单句实现无限层次父子关系查询

如何让MySQL中单句实现无限层次父子关系查询,第1张

表结构和数据

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)

查询 id = 5 的所有父级

SELECT ID.level, DATA.* FROM(

SELECT

@id as _id,

( SELECT @id := parent_id

FROM table1

WHERE id = @id

) as _pid,

select t1.name,t2.name,t3.name,t4.name

from tb as t1

left join tb as t2 on t2.pid=t1.id and t2.pid=1

left join tb as t3 on t3.pid=t2.id and t3.pid=2

left join tb as t4 on t4.pid=t3.id and t4.pid=3

where pid=0


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/8734325.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-20
下一篇 2023-04-20

发表评论

登录后才能评论

评论列表(0条)

保存