序列化表方法实现列转行
Posted ooo0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了序列化表方法实现列转行相关的知识,希望对你有一定的参考价值。
序列化表方法实现列转行
create table arms( id mediumint primary key auto_increment, user_name varchar(64), arms varchar(64), clothing varchar(64), shoe varchar(64) ); insert into arms(username,arms,clothing,shoe) values(‘唐僧‘,‘九环锡杖‘,‘袈裟‘,‘僧鞋‘),(‘孙悟空‘,‘金箍棒‘,‘黄金甲‘,‘步云鞋‘);
方法一:使用UNION的方法实现列转行
select user_name,‘arms‘,arms from arms union all select user_name,‘clothing‘,clothing from arms union all select user_name,‘shoe‘,shoe from arms;
方法二:使用序列化表的方法实现列转行
创建序列表:
create table tb_sequence(id int auto_increment not null,primary key(id)); insert into tb_sequence values(),(),(),(),(),(),(),(),();
SELECT user_name, CASE WHEN c.id = 1 THEN ‘arms‘ WHEN c.id = 2 THEN ‘clothing‘ WHEN c.id = 3 THEN ‘shoe‘ END AS equipment, COALESCE ( CASE WHEN c.id = 1 THEN arms END, CASE WHEN c.id = 2 THEN clothing END, CASE WHEN c.id = 3 THEN shoe END ) AS eq_name FROM arms b CROSS JOIN tb_sequence c WHERE c.id <= 3 ORDER BY user_name;
以上是关于序列化表方法实现列转行的主要内容,如果未能解决你的问题,请参考以下文章