Nấm Lùn
Nấm Lùn

Reputation: 1275

GROUP_CONCAT with LEFT JOIN condition?

Assume that I have these tables:

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

I want to get all data like this:

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

This is how I query the database:

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

But the result is not as I expected.

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

What was wrong with my query? I guess the problem is the [promos][product_ids] field but I have no idea to solve this.

Thanks in advance!

Upvotes: 2

Views: 1477

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

Storing comma separated ids is not a good idea see Database Normalization,you cannot simply use IN() to join with your set column for now you need to use FIND_IN_SET to find the values in a comma separated 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 

Upvotes: 2

Related Questions