原表如下: with t1 as( select 1 as id, "a,b" as course uNIOn select 2 as id, "a,b,c" as course unio
原表如下:
with t1 as( select 1 as id, "a,b" as course uNIOn select 2 as id, "a,b,c" as course union select 3 as id, null as course union select 4 as id, "c" as course)select * from t1;
id | course |
---|---|
1 | a,b |
2 | a,b,c |
3 | NULL |
4 | c |
需要将 course 按照 ‘,‘ 拆分成下表:
id | course |
---|---|
1 | a |
1 | b |
2 | a |
2 | b |
2 | c |
3 | NULL |
4 | c |
方法如下:
with t1 as( select 1 as id, "a,b" as course union select 2 as id, "a,b,c" as course union select 3 as id, null as course union select 4 as id, "c" as course)select t1.id, substring_index(substring_index(t1.course, ',', b.help_topic_id + 1), ',', -1) as coursefrom t1 join Mysql.help_topic bon b.help_topic_id < (length(t1.course) - length(replace(t1.course, ',', '')) + 1)union allselect id, coursefrom t1where course is null
这里主要用到 substring_index 和 mysql.help_topic。
SUBSTRING_INDEX 是字符串截取函数。
SUBSTRING_INDEX(str, delim, count)
例如:
SELECT SUBSTRING_INDEX('a*b*c*d', '*', 1); -- 返回: aSELECT SUBSTRING_INDEX('a*b*c*d', '*', 2); -- 返回: a*b SELECT SUBSTRING_INDEX('a*b*c*d', '*', 3); -- 返回: a*b*cSELECT SUBSTRING_INDEX('a*b*c*d', '*', 4); -- 返回: a*b*c*dSELECT SUBSTRING_INDEX('a*b*c*d', '*', -1); -- 返回: dSELECT SUBSTRING_INDEX('a*b*c*d', '*', -2); -- 返回: c*dSELECT SUBSTRING_INDEX('a*b*c*d', '*', -3); -- 返回: b*c*dSELECT SUBSTRING_INDEX('a*b*c*d', '*', -4); -- 返回: a*b*c*d
help_topic 本身是 MySQL 一个帮助解释注释表,用于解释 MySQL 各种专有名词,由于这张表数据 ID 是从 0 顺序增加的,方便我们用于计数,但是 8.0.17 版本的只有 686 条数据,超过这个数字,我们就需要己自定义一张表。
可以用做计数的临时表,查询的语句只会用 help_topic 计数,超出的部分其实都是脏数据。
如果不需要展开成多行,只需要计数,则可以将 ‘,‘ 替换成空,计算字符串的长度差。
selectid, length(course) - length(replace(course, ',', '')) + 1 as cntfrom t1
结果如下:
id | cnt |
---|---|
1 | 2 |
2 | 3 |
3 | NULL |
4 | 1 |
来源地址:https://blog.csdn.net/weixin_45545090/article/details/127109668
--结束END--
本文标题: 【SQL】按特定字符分割一行转多行
本文链接: https://www.lsjlt.com/news/375466.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-29
2024-04-29
2024-04-29
2024-04-29
2024-04-29
2024-04-29
2024-04-29
2024-04-28
2024-04-28
2024-04-28
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0