首頁  >  文章  >  資料庫  >  如何在 MySQL 中取得多行作為單一逗號分隔行?

如何在 MySQL 中取得多行作為單一逗號分隔行?

DDD
DDD原創
2024-11-14 13:49:02389瀏覽

How to Fetch Multiple Rows as a Single Comma-Separated Row in MySQL?

Fetching Multiple Rows as a Single Comma-Separated Row in MySQL

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:

  1. JOIN the "DISH_HAS_DISHES" (m) and "DISH" (d) tables based on the common dish_id field.
  2. Use GROUP_CONCAT(dish_id) to concatenate the dish IDs into a comma-separated string for each meal. Store this in the dish_ids column.
  3. Similarly, use GROUP_CONCAT(dish_name) to concatenate the dish names into a comma-separated string and store it in the dish_names column.
  4. GROUP BY meal_Id ensures that the results are grouped by meal ID, resulting in a single row for each meal.

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn