序列化表方法实现列转行

序列化表方法实现列转行

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; 

序列化表方法实现列转行_第1张图片

 

 

 

方法二:使用序列化表的方法实现列转行

创建序列表:

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;

序列化表方法实现列转行_第2张图片

 

 

 

 

 

你可能感兴趣的:(序列化表方法实现列转行)