Need Help with Hierarchical Mysql Query

前端 未结 3 1725
忘了有多久
忘了有多久 2020-12-21 23:23

I\'m trying to wrap my head around querying a table that has hierarchical category data (used for a cms) which is also tied to my posts data and a many-to-many type relation

3条回答
  •  隐瞒了意图╮
    2020-12-22 00:12

    There are perhaps better methods, but here's an idea:

    CREATE VIEW subcategories AS
    ( SELECT 0        AS level
           , cat_0.id AS cat_id
           , cat_0.id AS subcat_id
      FROM categories cat_0
    
      UNION ALL
    
      SELECT 1        AS level
           , cat_0.id AS cat_id
           , cat_1.id AS subcat_id
      FROM categories cat_0
        JOIN categories cat_1
          ON cat_0.id = cat_1.parent_id
    
      UNION ALL
    
      SELECT 2        AS level
           , cat_0.id AS cat_id
           , cat_2.id AS subcat_id
      FROM categories cat_0
        JOIN categories cat_1
          ON cat_0.id = cat_1.parent_id
        JOIN categories cat_2
          ON cat_1.id = cat_2.parent_id
    
      UNION ALL
    
      SELECT 3        AS level
           , cat_0.id AS cat_id
           , cat_3.id AS subcat_id
      FROM categories cat_0
        JOIN categories cat_1
          ON cat_0.id = cat_1.parent_id
        JOIN categories cat_2
          ON cat_1.id = cat_2.parent_id
        JOIN categories cat_3
          ON cat_2.id = cat_3.parent_id
    ) ;
    

    Then, use the above to have:

    SELECT sub.subcat_id
         , sub.level
         , p.post_id
         , p.title
    FROM subcategories sub
      JOIN post2cat p2c
        ON sub.subcat_id = p2c.cat_id
      JOIN posts p
        ON p2c.post_id = p.id
    WHERE sub.cat_id = CAT_ID        <--- the category id you want to search for
    

提交回复
热议问题