Mysql 通过其他行中的值排除行(获取树的叶子)

我有这张表:


+------------+-------------+------------------+

| product_id | category_id |  parent_category |

+------------+-------------+------------------+

|          1 |         aaa |                0 |

|          1 |         bbb |              aaa |

|          1 |         ccc |              bbb |

|          2 |         aaa |                0 |

|          2 |         bbb |              aaa |

|          2 |         ddd |                0 |

因此,我想排除同一类别中的父类别product_id,以便仅从表中获取最低级别的类别。parent_category 0意味着它是顶级类别(没有父级)


例如,第一行 withcategory aaa被排除,因为第二行中有一个类别bbb,并且aaa是bbb(product_id=1) 的父级。


期望的输出:


+------------+---------------+

| product_id |   category_id |

+------------+---------------+

|          1 |           ccc |          

|          2 |           bbb |           

|          2 |           ddd |

所以实际上类别结构就像aaa->bbb->ccc和ddd->eee->fff。aaa bbb ddd如果我想要获得类别中的产品bbb和ddd。


我的想法: php 正在使用中,所以我会创建肮脏的 php 循环。


编辑:澄清获取树叶是一个问题


qq_遁去的一_1
浏览 101回答 2
2回答

白猪掌柜的

所以当我做对了你想要得到一棵树的叶子。如果您没有严格限制,recursive CTE您可以简单地检查给定类别是否有子级。如果不是 - 它是一个叶子(尊重相同的product_id)。SELECT product_id, category_idFROM categories cWHERE    (        SELECT            count(*)        FROM            categories c2        WHERE            c2.parent_category = c.category_id            AND c2.product_id = c.product_id    ) = 0工作示例。如果你想检查product_id每个父母的情况,这将是行不通的。

慕村225694

尝试使用recursive CTE:with recursive cte as (      select         *, 0 as level, concat(product_id, '-', category_id) as ar       from         samp       where         parent_category ='0'union all      select         t1.*, t2.level+1, ar      from samp t1         inner join            cte t2         on t1.parent_category =t2.category_id and t1.product_id=t2.product_id),cte1 as (      select         *, row_number() over (partition by ar order by level desc) as rank_       from         cte          )    select         product_id, category_id, parent_category     from         cte1     where         rank_=1演示版
打开App,查看更多内容
随时随地看视频慕课网APP