在项目中用到了MySQL数据库行转列功能,记录一下,以防忘记:
转载自:https://blog.csdn.net/github_33809414/article/details/86656216
准备:
在MySQL数据库中新建一张测试表,表中列的内容使用逗号隔开:
MySQL行转列语句:
SELECT DISTINCT
(
substring_index(
substring_index(
a.col,
',',
b.help_topic_id + 1
),
',' ,- 1
)
) AS `test3` #表名
FROM
(
SELECT
group_concat(DISTINCT `name`) AS col #name为用逗号隔开的列名
FROM
`test3` #表名
) AS a
JOIN mysql.help_topic AS b ON b.help_topic_id < (
char_length(a.col) - char_length(REPLACE(a.col, ',', '')) + 1
)
#sql语句中的列可以替换成字符串或者查询语句
运行结果: