代码缝合 2022-04-23 16:43 采纳率: 22.2%
浏览 39
已结题

一个表中有自身id,父亲id,母亲id 如何追溯4代

一个表中有自身id,父亲id,母亲id 如何追溯4代,最终还是要三列,只是要追溯四代

  • 写回答

1条回答 默认 最新

  • 三千烦恼丝xzh 2022-04-23 22:20
    关注

    MySQL8+ CTE递归

    with recursive cte as (
    select p, father, mother, 1 count from table_name where p = 'pid'
    union all 
    select t1.p, t1.father, t1.mother, c.count +1 from table_name t1, cte c where c.father = t1.p or c.mother = t1.p
    ) select * from cte where count <= 4
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 5月2日
  • 已采纳回答 4月24日
  • 创建了问题 4月23日