Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL : Multiple row as comma separated single row

Tags:

database

mysql

I have two tables : DISH and DISH_HAS_DISHES. Dish table has all the dishes and "Dish_has_dishes" table has a one-to-many relationship with "Dish" table. I.e. a dish can have multiple dishes. For example

DISH :

dish_id   dish_name 1         dish_1 2         dish_2 3         dish_3 4         dish_4 

DISH_HAS_DISHES :

meal_id   dish_id 1         2 1         3 1         4 

Here meal_id and dish_id both are IDs from DISH table. Now I want a format like this:

meal_id     dish_ids     dish_names 1           2,3,4        dish_2, dish_3, dish_4 

That is comma separated dish id and names for each meal. How to do that?

like image 486
Swar Avatar asked Aug 16 '10 11:08

Swar


People also ask

How do I combine multiple rows into one in MySQL?

The GROUP_CONCAT() function in MySQL is used to concatenate data from multiple rows into one field. This is an aggregate (GROUP BY) function which returns a String value, if the group contains at least one non-NULL value. Otherwise, it returns NULL.

How do I get row values as comma separated by a query in MySQL?

In MySQL, you can return your query results as a comma separated list by using the GROUP_CONCAT() function. The GROUP_CONCAT() function was built specifically for the purpose of concatenating a query's result set into a list separated by either a comma, or a delimiter of your choice.


1 Answers

Use GROUP_CONCAT FUNCTION

http://dev.mysql.com/tech-resources/articles/4.1/grab-bag.html

 SELEct m.meal_Id,          GROUP_CONCAT(dish_id) dish_ids,          GROUP_CONCAT(dish_name) dish_names  FROM DISH_HAS_DISHES m JOIN DISH d ON (m.dish_id = d.dish_id)  GROUP BY meal_Id 
like image 70
Michael Pakhantsov Avatar answered Sep 17 '22 18:09

Michael Pakhantsov