栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在MySQL中将一列拆分为多列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在MySQL中将一列拆分为多列

使用给定的示例数据,您可以执行以下操作-

mysql> create table test (marks varchar(100));Query OK, 0 rows affected (0.12 sec)mysql> insert into test values ('Maths-80,Phy-100,Che-99'),('Maths-90,Phy-60'),('Phy-82,Che-65'),('Che-90'),('Maths-33,Phy-89,Che-65'),('Maths-50,Phy-43,Che-59');Query OK, 6 rows affected (0.04 sec)Records: 6  Duplicates: 0  Warnings: 0mysql> select * from test ;+-------------------------+| marks        |+-------------------------+| Maths-80,Phy-100,Che-99 || Maths-90,Phy-60         || Phy-82,Che-65|| Che-90       || Maths-33,Phy-89,Che-65  || Maths-50,Phy-43,Che-59  |+-------------------------+6 rows in set (0.00 sec)

现在使用

locate
substring_index
我们可以将值提取为

select marks, case  when locate('Maths',marks) > 0 then substring_index(substring_index(marks,'Maths-',-1),',',1) else 0 end as Maths ,case  when locate('Phy',marks) > 0 then substring_index(substring_index(marks,'Phy-',-1),',',1) else 0 end as Phy ,case  when locate('Che',marks) > 0 then substring_index(substring_index(marks,'Che-',-1),',',1) else 0 end as Che from test ;

输出 :

+-------------------------+-------+------+------+| marks        | Maths | Phy  | Che  |+-------------------------+-------+------+------+| Maths-80,Phy-100,Che-99 | 80    | 100  | 99   || Maths-90,Phy-60         | 90    | 60   | 0    || Phy-82,Che-65| 0     | 82   | 65   || Che-90       | 0     | 0    | 90   || Maths-33,Phy-89,Che-65  | 33    | 89   | 65   || Maths-50,Phy-43,Che-59  | 50    | 43   | 59   |+-------------------------+-------+------+------+6 rows in set (0.00 sec)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660244.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号