XY BLOG

XY的BLOG

MySQL 递归查询 WITH RECURSIVE

Published on in Posts
Updated on
Short link: https://b.xyzt07.cn/s/c
Share this post
A ⇄ 文
⚠️ This entry is already over one year old. It may no longer be up to date. Opinions may have changed.

查询user推荐关系下的指定层级子集

WITH RECURSIVE promotion_tree AS (
  SELECT id,  parent_id,1 as level
  FROM fa_user  WHERE  id = 4
	UNION 
	SELECT pu.id,pu.parent_id,pt.level+1  FROM fa_user pu join promotion_tree pt on pu.parent_id=pt.id  and pt.level<4
)
SELECT *
FROM promotion_tree;