MySQL查询语句之【排序 去重 分组】

本文详细介绍了MySQL中的排序(ASC, DESC)、去重(union, distinct)和分组(group by)操作,包括升序和降序排序、保留重复数据与去重、以及基本分组、计数、求和与空值处理。通过实例演示了如何在实际项目中使用这些技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.MySQL排序:(order by

1.升序 :ASC(默认)

语法:select * from 数据表名 order by 字段名 ASC;

2. 降序: DESC

语法:select * from 数据表名 order by 字段名 DESC;

-- 排序 默认升序
select * from mytable2 order by brith ;

-- 降序排序
select * from mytable2 order by brith DESC;

-- 升序排序
select * from mytable2 order by brith ASC;

2.MySQL去重:(union

语法 :select * from table1 [where子句] union select * from table2 [where子句];

      union 后可加all ,也可加distinct。默认为 union distinct。

1.select * from table1 [where子句] union all select * from table2 [where子句];

        保留结果集中重复的数据。

2.select * from table1 [where子句] union distinct select * from table2 [where子句];

        删除结果集中重复的数据,每条数据只保留一条。

 3.MySQL分组:(group by

1.简单分组并统计每组个数:group by

-- 按照名字分组 并显示每组个数
select name ,count(*) AS '个数' from employee_tbl GROUP BY name ;

2.显示每组signin字段的和:with rollup 再次统计

-- 按照名字分组后再统计signin的总数
select name,sum(signin) from employee_tbl GROUP BY name with rollup;

3.为空值设置name:coalesce()函数

-- coalesce(a,b,c)函数 如果a为空就取b值,b为空就取c值,c为空就返回null
select coalesce (name,'总数') ,sum(signin) from employee_tbl group by name with rollup;

        coalesce() 与 ifnull()两函数的区别:ifnull函数只能接收两个参数,意义为:如果第一个为空,则选择第二个参数;而coalesce函数可以接收两个或多个参数,如果第一个为空,则选择第二个参数,第二个为空则选择第三个参数... ...以此类推。

        if(expr,值1, 值2):如果expr为true,返回值1;否则,返回值2;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值