开发者

MySQL - Displaying results from a sub-query in a single row

I have two tables, products and category. A product can be in multiple categories.

product (<product_id>, name, desc, price)
category (<category_id>, slug, display_name)
product_category(<category_id>, <product_id>)

Product have a N:M relationship with category. I would like a query which show the categories of the product in a single row, like this

name           |   desc                           | categories
------------------------------------------------------------------
The One Ring     One ring to rule them all          Magical Item, Jewelry

Where Magical Item is one category, and Jewelry is another (Not real life example. Sauron is not asking me to set up shop).

So I am thinking of:

SELECT name, desc, categories.display_name FROM product, category, 
category_product  WHERE product.product_id  = category_product.product_id AND
category_product.category_id = category.category_id

However, this will result in the item being listed more than once if it belongs to multiple categories. How to lump all the categories just into o开发者_C百科ne row?


Use:

  SELECT p.name,
         p.desc,
         GROUP_CONCAT(c.display_name) AS categories
    FROM PRODUCT p
    JOIN PRODUCT_CATEGORY pc ON pc.product_id = p.product_id
    JOIN CATEGORY c ON c.category_id = pc.category_id
GROUP BY p.name, p.desc
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜