如何在mysql中使用Group by

时间:2014-12-21 03:02:38

标签: mysql

我正在使用此SQL查询从DB获取产品列表。

SELECT distinct P.product_id, B.brand_name, P.product_name,  P.product_description,   SC.sub_category_name, P.product_image_path
FROM table_products as P
INNER JOIN table_brands as B 
ON P.brand_id = B.brand_id

INNER JOIN table_product_categories as PC 
ON P.product_id = PC.product_id


INNER JOIN table_subcategories as SC
ON SC.sub_categories_id = PC.category_id

INNER JOIN table_subcategory_categories as SCC
ON SC.sub_categories_id = SCC.subcategory_id
ORDER BY P.product_id DESC";

对我来说很好。但是当同一产品属于多个子类别时。它给了我一个新的排。我只是想避免这种情况,并希望GROUP by SC.sub_category_name。因此,当产品属于多个类别时,所有类别应列在同一行中。

当前

  1. 853 Tops Premium Vermicelli /images/tops/853.png Noodles
  2. 853 Tops Premium Vermicelli /images/tops/853.png Vermicelli
  3. 期待

    1. 853 Tops Premium Vermicelli /images/tops/853.png Noodles,Vermicelli

1 个答案:

答案 0 :(得分:1)

您可以将GROUP_CONCAT()用于此目的,按SC.sub_category_name进行分组,然后移除distinct。像

这样的东西
SELECT P.product_id, 
B.brand_name, 
P.product_name,  
P.product_description,   
GROUP_CONCAT(SC.sub_category_name) as sub_cat_list, 
P.product_image_path
FROM table_products P
INNER JOIN table_brands B 
ON P.brand_id = B.brand_id

INNER JOIN table_product_categories PC 
ON P.product_id = PC.product_id


INNER JOIN table_subcategories SC
ON SC.sub_categories_id = PC.category_id

INNER JOIN table_subcategory_categories SCC
ON SC.sub_categories_id = SCC.subcategory_id
GROUP BY P.product_id
ORDER BY P.product_id DESC;