GROUP_CONCAT与LEFT JOIN条件?

时间:2014-06-10 05:01:43

标签: mysql left-join group-concat

假设我有这些表:

categories

id   name           parent_id
1    Category 1     0     
2    Category 2     1
3    Category 3     1
4    Category 4     2 


products

id   name                 category_id
1    product name 1       2        
2    product name 2       2
3    product name 3       3 
4    product name 4       4


promos

id   product_ids
1    1,2,3
2    1,4
3    2,3
4    4

我想得到这样的所有数据:

product_id   product_name       promo_ids
1            product name 1     1,2
2            product name 2     1,3
3            product name 3     1,3
4            product name 4     2,4

这是我查询数据库的方式:

SELECT GROUP_CONCAT(pr.id) as promo_ids, p.id as product_id, p.name as product_name, 
FROM `products` as p
LEFT JOIN `promos` as pr ON `p`.`id` IN (pr.product_ids)
WHERE p.category_id IN(1,2,3,4)
GROUP BY p.id

但结果并不像我预期的那样。

product_id   product_name       promo_ids
1            product name 1     
2            product name 2     
3            product name 3     
4            product name 4   

我的查询有什么问题?我想问题是[promos] [product_ids]字段,但我不知道解决这个问题。

提前致谢!

1 个答案:

答案 0 :(得分:2)

存储逗号分隔的ID不是一个好主意,请参阅Database Normalization,您不能简单地使用IN()加入您的设置列,现在您需要使用FIND_IN_SET来查找值逗号分隔的集合

SELECT 
  GROUP_CONCAT(pr.id ORDER BY pr.id) AS promo_ids,
  p.id AS product_id,
  p.name AS product_name 
FROM
  `products` AS p 
  LEFT JOIN `promos` AS pr 
    ON FIND_IN_SET(`p`.`id`,pr.product_ids) 
WHERE p.category_id IN (1, 2, 3, 4) 
GROUP BY p.id