How to JOIN category table for parents in SQL query?

前端 未结 2 1697
别那么骄傲
别那么骄傲 2021-01-16 18:41

I have a table for posts as (id, category_id, ...), then JOIN it with the category table as (category_id, category_name, parent, ...) ON category_id

相关标签:
2条回答
  • 2021-01-16 19:22

    If you're willing to limit the depth, you can use UNION to stack up JOINs to get what you want. Here's a 3-level deep implementation:

    select * from posts
    where category_id = ?
    union
    select * from posts p
    join category c on c.category_id = p.category_id
    where c.parent = ?
    union
    select * from posts p
    join category c1 on c1.category_id = p.category_id
    join category c2 on c2.category_id = c1.parent
    where c2.parent = ?
    

    You would pass the same variable in (for the category you're interested in) for all 3 placeholders.

    0 讨论(0)
  • 2021-01-16 19:35

    Just do an additional join for the extra element, but have IT as a LEFT join as not all categories have a parent category and you don't want to exclude those.

    select
          P.ID,
          P.Post_Title,
          P.Category_ID,
          C.Category_Name as FirstCat,
          C.Parent,
          COALESCE( C2.Category_Name, ' ' ) as ParentCategory
       from
          Posts P
             JOIN Categories C
                on P.Category_ID = C.Category_ID
                LEFT JOIN Categories C2
                   on C.Parent = C2.Category_ID
       where
          AnyFiltering
    
    0 讨论(0)
提交回复
热议问题