SQL to join one table to another table multiple times? (Mapping products to categories)

前端 未结 4 1984
北海茫月
北海茫月 2021-02-04 19:54

Let\'s say I have a Product, Category, and Product_To_Category table. A Product can be in multiple categories.

    Product             


        
4条回答
  •  爱一瞬间的悲伤
    2021-02-04 19:59

    I don't know what RDBMS you're using, but in MySQL you can use GROUP_CONCAT:

    SELECT
      p.name,
      GROUP_CONCAT(c.name SEPARATOR ', ') AS categories
    FROM
      product p
      JOIN product_to_category pc ON p.id = pc.product_id
      JOIN category c ON c.id = pc.category_id
    GROUP BY
      p.name
    ORDER BY
      p.name,
      c.name
    

提交回复
热议问题