接上篇,上篇介绍了我面试遇到的MySQL行转列的笔试题,本篇将拓展一下行列互转的其他知识。
建表语句:
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慢很多;