在 sql server 中,使用 cte 表达式很容易做到无限层次父子关系查询;在不支持cte表达式的版本中,借助函数递归也可以轻松实现。
在 mysql 中,这个需求的实例稍显复杂, mysql 中没有支持递归的查询,没有表值函数,函数不支持递归,所以通常都是用循环实现,显得比较别扭。今天看到一个用单条语句实现的递归查询,想法独特,分享一下。
相关mysql视频教程推荐:《mysql教程》
表结构和数据
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中单句实现无限层次父子关系查询,更多相关内容请关注。
相关推荐:
带进度的sql server filestream如何存取
当忘记 sql server 管理员密码该如何处理
浅析mysql中concat以及group_concat的使用
以上就是如何让mysql中单句实现无限层次父子关系查询的详细内容。