亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 125 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號