MySQL行列转换——列转行(二)

接上篇,上篇介绍了我面试遇到的MySQL行转列的笔试题,本篇将拓展一下行列互转的其他知识。


原表.png
新表.png

建表语句:

create table score_2(
id VARCHAR(3),
cn_score float,
math_score float,
en_score float
);
insert INTO score_2 VALUES('001',90,92,80);
insert INTO score_2 VALUES('002',88,90,75.5);
insert INTO score_2 VALUES('003',70,85,90);

行转列实现:

select id,'chinese' as course,cn_score as score from score_2
union ALL
select id,'math' as course,math_score as score from score_2
union ALL
select id,'english' as course,en_score as score from score_2
order by id;

注意:union 与union all 的区别

  • 对重复结果的处理:union会去掉重复结果,union all 不会;
    *对排序的处理:union会排序,union all 不会,只是简单的将两个结果集合并;
    *效率方面:因为union会做去重和排序的操作,因此效率比union all慢很多;
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容