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

如何修改MySQL数据查询逻辑实现多服务类型列转单列行输出

MySQL宽表转长表解决方案

你可以使用UNION ALL实现多列拆分为多行的需求,该写法兼容所有MySQL版本,替换实际表名后即可直接运行:

SELECT 
  Family AS family,
  Members AS Member,
  `type of service 1` AS `Type of service`
FROM 你的实际表名
UNION ALL
SELECT 
  Family AS family,
  Members AS Member,
  `Type of Service 2` AS `Type of service`
FROM 你的实际表名
UNION ALL
SELECT 
  Family AS family,
  Members AS Member,
  `Type of service 3` AS `Type of service`
FROM 你的实际表名
-- 可选:按家庭、成员排序输出
ORDER BY family, Member;

如果你使用的是MySQL 8.0及以上版本,也可以用更简洁的UNPIVOT语法实现:

SELECT 
  Family AS family,
  Members AS Member,
  service_type AS `Type of service`
FROM 你的实际表名
UNPIVOT (
  service_type FOR service_column IN (
    `type of service 1`, 
    `Type of Service 2`, 
    `Type of service 3`
  )
) AS unpivoted_result;

注意:原表的服务类型列名包含空格,所以需要用反引号包裹避免语法报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:54:08