MySQL开发技巧(二)

课程地址:https://www.imooc.com/learn/427

第1章 课程介绍

1-1 MySQL开发技巧(二)课程介绍

image

第2章 如何进行行列转换

2-1 MySQL-行转列场景介绍

image
image

2-2 MySQL-需求分析

image

2-3 MySQL-使用自连接的方法实现行转列

select a.`user_name`,kills from user1 a join user_kills b on a.id=b.user_id;

​select a.`user_name`,sum(kills) from user1 a join user_kills b on a.id=b.user_id group by a.user_name;
​
​select a.`user_name`,sum(kills) from user1 a join user_kills b on a.id=b.user_id group by a.user_name='孙悟空';

select * from (
  select sum(kills) as '孙悟空' from user1 a join user_kills b on a.id=b.user_id group by a.user_name='孙悟空';
) a cross join (
    select sum(kills) as '猪八戒' from user1 a join user_kills b on a.id=b.user_id group by a.user_name='猪八戒';
) b cross join (
    select sum(kills) as '沙僧' from user1 a join user_kills b on a.id=b.user_id group by a.user_name='沙僧';
) c

2-4 MySQL-使用CASE方法实现行转列

select a.`user_name`,kills from user1 a join user_kills b on a.id=b.user_id;

select sum(case when user_name='孙悟空' then kill end) as '孙悟空',
  sum(case when user_name='猪八戒' then kill end) as '猪八戒',
  sum(case when user_name='沙僧' then kill end) as '沙僧'
 from user1 a join user_kills b on a.id = b.user_id;

2-5 MySQL-单列转多行场景介绍

image
image

2-6 MySQL-使用序列化表的方法实现行转列

image

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

image

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;

2-8 MySQL-使用序列化表的方法实现列转行

​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 user1 a
join user1_equipment b on a.id = b.user_id
cross join tb_sequence c where c.id <= 3 order by user_name;

第3章 如何生成唯一序列号

3-1 MySQL-在数据库中立唯一序列号的常用方法

image
image
image

3-2 如何使用SQL语句建立特殊需求的序列号

image
image

第4章 如何删除重复数据

4-1 MySQL-利用主键删除重复数据

image
image
image

4-2 MySQL-如何处理复杂的重复数据删除

image

posted @ 2025-10-09 08:37  hwq1992  阅读(3)  评论(0)    收藏  举报