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 |
以上是如何在 MySQL 中取得多行作為單一逗號分隔行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!