Home > Database > Mysql Tutorial > How Can MySQL's GROUP BY Clause Concatenate Strings?

How Can MySQL's GROUP BY Clause Concatenate Strings?

Susan Sarandon
Release: 2025-01-21 20:41:11
Original
437 people have browsed it

How Can MySQL's GROUP BY Clause Concatenate Strings?

MySQL's GROUP BY Clause: Combining Strings

MySQL's powerful GROUP BY clause isn't limited to numerical aggregation. It can also efficiently concatenate strings associated with grouped data. This is especially helpful when dealing with tables containing multiple rows sharing a common identifier.

Consider this example table:

foo_id foo_name
1 A
1 B
2 C

Our goal is to combine foo_name values for each unique foo_id, resulting in:

foo_id foo_name
1 A, B
2 C

This transformation is achieved using the following SQL query:

<code class="language-sql">SELECT foo_id, GROUP_CONCAT(foo_name SEPARATOR ', ') FROM table GROUP BY foo_id;</code>
Copy after login

Query Explanation:

  • GROUP BY foo_id: This groups rows based on the foo_id column, bringing together all foo_name values for each unique ID.
  • GROUP_CONCAT(foo_name SEPARATOR ', '): This function concatenates the foo_name values within each group, using a comma and space as the separator.

The GROUP_CONCAT() function offers a SEPARATOR argument, allowing flexible customization of the delimiter between concatenated strings. For comprehensive details, refer to the official MySQL documentation: https://www.php.cn/link/18fc3b6cc1e55ccea877c161e2e9ba27

The above is the detailed content of How Can MySQL's GROUP BY Clause Concatenate Strings?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template