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>
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!