简体   繁体   中英

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 one 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM