You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否可使用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 Name and uses GROUP_CONCAT to merge all Brcode values for that group into a comma-separated string. Adding ORDER BY Brcode ensures the values are sorted numerically (matching your sample's 1,2,3 order instead of a random sequence).
  • We join this subquery result back to the original table using the Name column. This attaches the concatenated list to every row in the original table that belongs to the same Name group.

Testing with your sample data:

If your table starts with:

BrcodeName
1A
2A
3A

Running the query will produce exactly your desired output:

BrcodeNameCommon
1A1,2,3
2A1,2,3
3A1,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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 14:37:37