Skip to main content

Mysql function: GROUP_CONCAT() (Like implode() in php)

Today i have to solve a problem in MySql , The problem is i have two table in openCart
1. category_description
category_id language name
1 1 category 1
2 1 category 2
3 1 category 3
4 1 category 4
5 1 category 5
6 1 category 6
7 1 category 7
8 1 category 8
1. product_category
produc_idcategory_id
11
12
15
21
23
24
32
36
The resulting data should be like that
produc_idcategory_name
1category 1,category 2,category 5
2category 1,category 3,category 4
3category 2,category 6

I can do tha by in php by taking the category name to it's respective product id and implode them , but it will take much time and processor power cos the i have to do query every product id separately, I was searching the right query in MySql and found the function   GROUP_CONCAT() http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

SELECT pc.product_id,GROUP_CONCAT(DISTINCT cd.name) category_name FROM product_to_category pc LEFT JOIN category_description cd ON (pc.category_id=cd.category_id) WHERE cd.language_id =1 GROUP BY pc.product_id And made the query i was looking for and solved my problem :)

Mysql function: GROUP_CONCAT()  (Like implode() in php)

Comments

Post a Comment