Problem Statement:
You have two tables, "DISH" and "DISH_HAS_DISHES," where dishes are related with a one-to-many dependency. The goal is to retrieve data from both tables in a specific format: a comma-separated list of dish IDs and names for each meal.
Proposed Solution with GROUP_CONCAT Function:
MySQL provides the GROUP_CONCAT function, which allows for the concatenation of multiple rows based on a specified delimiter. Utilizing this function, you can achieve the desired output:
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
Explanation:
This query should produce the desired output format:
meal_id | dish_ids | dish_names |
---|---|---|
1 | 2,3,4 | dish_2, dish_3, dish_4 |
The above is the detailed content of How to Fetch Multiple Rows as a Single Comma-Separated Row in MySQL?. For more information, please follow other related articles on the PHP Chinese website!