表结构和数据
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, @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
本文讲解了如何让MySQL中单句实现无限层次父子关系查询,更多相关内容请关注php中文网。
相关推荐:
浅析MySQL中concat以及group_concat的使用
以上就是如何让MySQL中单句实现无限层次父子关系查询的详细内容,更多请关注php中文网其它相关文章!
……