Combining Duplicate Entries in MySQL Using GROUP_CONCAT
This guide explains how to merge rows with identical foo_id
values, concatenating their corresponding foo_name
entries into a single string within a MySQL table.
The Solution: GROUP_CONCAT and GROUP BY
MySQL's GROUP_CONCAT
function, used in conjunction with GROUP BY
, efficiently solves this problem. Here's the query:
<code class="language-sql">SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;</code>
Query Breakdown:
SELECT id, GROUP_CONCAT(name SEPARATOR ' ')
: This selects the id
column and uses GROUP_CONCAT
to combine the name
column values for each group. The SEPARATOR ' '
specifies a space as the delimiter between concatenated names.FROM table
: Indicates the table containing the data.GROUP BY id
: Groups the rows based on the unique values in the id
column.How it Works:
GROUP_CONCAT
aggregates non-NULL values from each group defined by GROUP BY
. The separator ensures readability by placing spaces between the concatenated names. This effectively merges rows with the same id
, creating a single row with all associated names combined into one string.
Further Reading:
For more comprehensive information on GROUP_CONCAT
, consult the official MySQL documentation: https://www.php.cn/link/18fc3b6cc1e55ccea877c161e2e9ba27
The above is the detailed content of How Can I Concatenate Strings in MySQL Using GROUP BY?. For more information, please follow other related articles on the PHP Chinese website!