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

如何将MySQL查询结果合并为单个单元格?

合并查询结果为单个单元格

原始查询语句

SELECT namaline, shift1 FROM semualine WHERE cektelatshift1 <> 'Ontime' UNION
SELECT namaline, shift2 FROM semualine WHERE cektelatshift2 <> 'Ontime' UNION
SELECT namaline, shift3 FROM semualine WHERE cektelatshift3 <> 'Ontime';

当前查询结果

namalineshift1
Line 1Shift 1
Line 2Shift 1
Line 3Shift 1
Line 1Shift 2
Line 2Shift 2
Line 3Shift 2
Line 1Shift 3
Line 2Shift 3

需求与预期结果

希望将上述所有查询结果合并到单个单元格中,预期结果如下:

1 cell
Line 1 Shift 1, Line 2 Shift 1, Line 3 Shift 1, Line 1 Shift 2, Line 2 Shift 2, Line 3 Shift 2, Line 1 Shift 3, Line 2 Shift 3

解决方案

以MySQL为例,使用GROUP_CONCAT函数实现合并,先通过子查询统一列名并拼接字段,再合并所有结果:

SELECT GROUP_CONCAT(CONCAT(namaline, ' ', shift_col) SEPARATOR ', ') AS `1 cell`
FROM (
    SELECT namaline, shift1 AS shift_col FROM semualine WHERE cektelatshift1 <> 'Ontime'
    UNION
    SELECT namaline, shift2 AS shift_col FROM semualine WHERE cektelatshift2 <> 'Ontime'
    UNION
    SELECT namaline, shift3 AS shift_col FROM semualine WHERE cektelatshift3 <> 'Ontime'
) AS combined_results;

说明:

  • 子查询将三个UNION语句的班次列统一命名为shift_col,保证数据结构一致
  • CONCAT(namaline, ' ', shift_col)把每条记录的生产线和班次拼接成单个字符串
  • GROUP_CONCAT将所有拼接后的字符串用逗号分隔,最终合并为单个单元格内容

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 22:55:56