MySQL递归查询之with recursive

现有表region
含有以下数据
在这里插入图片描述
要查询中国的所有区域并包含中国

# tmp中内容可省略
with recursive tmp(id,name,parent_id,parent_name) as (
	select r1.*,r2.name as parent_name from region r1 
	inner join region r2 on r1.id = r2.id
	where r1.id = 1 
	union all 
	select r3.*,tmp.name from region r3 
	inner join tmp on r3.parent_id = tmp.id
)
select * from tmp

注意:
tmp表示临时表
union all 或 union:对两个结果集进行并集操作,操作前后的表字段数量要保持一致
union 和 union all 的区别是,union 会自动压缩多个结果集合中的重复结果,而 union all 则将所有的结果全部显示出来,不管是不是重复。

猜你喜欢

转载自blog.csdn.net/weixin_43636205/article/details/130134324