2-7 MySQL-使用UNION的方法实现列转行

select user_name,'arms' as equipment,arms from user1 a join user1_equipment b on a.id=b.user_id union all select user_name,'clothing' as equipment,clothing from user1 a join user1_equipment b on a.id=b.user_id union all select user_name,'shoe' as equipment,shoe from user1 a join user1_equipment b on a.id=b.user_id order by user_name;
多条sql连接查询
UNION ALL 操作用于结合两个或更多 SELECT 语句的结果集,包括所有匹配的行,甚至包括重复的行。这与 UNION 不同,因为 UNION 会自动删除重复的行。
满足条件:
1、两个select查询的列的数量必须相同。
2、每个列的数据类型需要相似。
多列转行SQL语句

使用union的方法实现列转行
备注:当连接表变多时,使用序列号进行列转行优于union
需要进行列转行的另一种场景
列转行语法
列转行的场景2
列转行的方式。序列化:
列转行的另外一种:

使用UNION方法实现列转行
SELECT user_name,'arms' AS equipment,arms FROM user1 a JOIN user1_equipment b ON a.id=b.user_id UNION ALL SELECT user_name,'clothing' AS equipment,clothing FROM user1 a JOIN user1_equipment b ON a.id=b.user_id
union的方法实现列转行
@MySQL---使用UNION方法实现列转行
SELECT user_name,'arms' AS equipment,arms FROM user1 a JOIN user1_equipment b ON a.id=b.user_id UNION ALL SELECT user_name,'clothing' AS equipment,clothing FROM user1 a JOIN user1_equipment b ON a.id=b.user_id UNION ALL SELECT user_name,'shoe' AS equipment,shoe FROM user1 a JOIN user1_equipment b ON a.id=b.user_id ORDER BY user_name;
create table arms( id mediumint primary key auto_increment, username varchar(64), arms varchar(64), clothing varchar(64), shoe varchar(64) ); insert into arms(username,arms,clothing,shoe) values('唐僧','九环锡杖','袈裟','僧鞋'),('孙悟空','金箍棒','黄金甲','步云鞋'); select username,'arms',arms from arms union all select username,'clothing',clothing from arms union all select username,'shoe',shoe from arms;