为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
qq_遁去的一_1 2023-10-21 16:34:41
我有这张表:+------------+-------------+------------------+| 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 循环。编辑:澄清获取树叶是一个问题
查看完整描述

2 回答

?
白猪掌柜的

TA贡献1893条经验 获得超10个赞

所以当我做对了你想要得到一棵树的叶子。如果您没有严格限制,recursive CTE您可以简单地检查给定类别是否有子级。如果不是 - 它是一个叶子(尊重相同的product_id)。


SELECT product_id, category_id

FROM categories c

WHERE

    (

        SELECT

            count(*)

        FROM

            categories c2

        WHERE

            c2.parent_category = c.category_id

            AND c2.product_id = c.product_id

    ) = 0

工作示例

如果你想检查product_id每个父母的情况,这将是行不通的。


查看完整回答
反对 回复 2023-10-21
?
慕村225694

TA贡献1880条经验 获得超4个赞

尝试使用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

演示版


查看完整回答
反对 回复 2023-10-21
  • 2 回答
  • 0 关注
  • 58 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信