是否可使用GROUP_CONCAT实现指定的数据库分组拼接结果?
Yes, you can use GROUP_CONCAT to achieve this result!
Absolutely—this is a perfect use case for combining GROUP_CONCAT with a subquery to propagate the concatenated list across all rows in a group. Here's how to do it:
SELECT original.Brcode, original.Name, grouped.Common FROM your_table original INNER JOIN ( -- Subquery to generate the concatenated Brcode list per Name group SELECT Name, GROUP_CONCAT(Brcode ORDER BY Brcode SEPARATOR ',') AS Common FROM your_table GROUP BY Name ) grouped ON original.Name = grouped.Name;
Breakdown of how this works:
- The inner subquery groups rows by
Nameand usesGROUP_CONCATto merge allBrcodevalues for that group into a comma-separated string. AddingORDER BY Brcodeensures the values are sorted numerically (matching your sample's1,2,3order instead of a random sequence). - We join this subquery result back to the original table using the
Namecolumn. This attaches the concatenated list to every row in the original table that belongs to the sameNamegroup.
Testing with your sample data:
If your table starts with:
| Brcode | Name |
|---|---|
| 1 | A |
| 2 | A |
| 3 | A |
Running the query will produce exactly your desired output:
| Brcode | Name | Common |
|---|---|---|
| 1 | A | 1,2,3 |
| 2 | A | 1,2,3 |
| 3 | A | 1,2,3 |
For a more compact (though potentially less efficient for large datasets) alternative, you can use a correlated subquery:
SELECT Brcode, Name, (SELECT GROUP_CONCAT(Brcode ORDER BY Brcode) FROM your_table WHERE Name = t.Name) AS Common FROM your_table t;
Both methods will give you the result you're looking for!
内容的提问来源于stack exchange,提问作者Papsi Rhty
相关产品推荐
相关产品推荐

