前提:测试数据
id | age | name |
---|---|---|
1 | 12 | 张三 |
2 | 32 | 李四 |
3 | 22 | 王五 |
4 | NULL | 赵六 |
5 | 12 | 杨七 |
关键字
1、数据排序:DESC/ASC
单一字段排序
默认升序ASC
select * from user order by id;
执行结果:
id age name
1 12 张三
2 32 李四
3 22 王五
4 NULL 赵六
5 12 杨七
手动降序DESC:
select * from user order by id desc;
执行结果:
id age name
5 12 杨七
4 NULL 赵六
3 22 王五
2 32 李四
1 12 张三
多个字段排序
注意: 如果采用多个字段排序,如果根据第一个字段排序重复了,会根据第二个字段排序;
select * from user order by age desc,id desc;
执行结果:
id age name
2 32 李四
3 22 王五
5 12 杨七
1 12 张三
4 NULL赵六
注意:错误写法
以下sql降序根本没有生效:注意
select * from user order by age,id desc;
执行结果:
id age name
4 NULL赵六
5 12 杨七
1 12 张三
3 22 王五
2 32 李四
2、去重:DISTINCT
作用于单列
select distinct age from user;
执行结果:
age
12
32
22
NULL
作用于多列
实际上是根据age和name两个字段来去重的:
select distinct age,name from user;
执行结果:
age name
12 张三
32 李四
22 王五
NULL 赵六
12 杨七
注意:并非是对age和name两列“字符串拼接”后再去重的,而是分别作用于了age和name列。例如下:
测试数据:
id age name
5 12 杨七
6 2 2杨七
select distinct age,name from user;
执行结果:
12 杨七
2 2杨七
COUNT统计
表中age去重后的数目,并且过滤NULL
select count(distinct age) from user;
执行结果:3
会通过表中age和name字段去重后统计行数
注意:如果去重字段存在NULL的情况,会过滤,以下就没有统计出name=赵六,因为age=NULL
select count(distinct age,name) from user;
执行结果:4
DISTINCT必须放在开头
会提示错误,因为distinct必须放在开头
select name,distinct age from user;
其他
distinct语句中select显示的字段只能是distinct指定的字段,其他字段是不可能出现的。
例如:想获取distinct age,以及对应的name字段,想直接通过distinct是不可能实现的。
select distinct age from user;
执行结果:
age
12
32
22
NULL
函数
1、字符串拼接:CONCAT()
select concat('1,',null,'2');
执行结果: NULL
select concat('1,','','2');
执行结果: 1,2
注意:CONCAT函数拼接时如果拼接中的参数只要有NULL时,结果为NULL
方法一:使用IFNULL函数如果是NULL将其置为’'空字符串
select concat('1,',ifnull(null,''),'2');
执行结果:1,2
方法二:使用CONCAT_WS函数。指定有分隔符的字符串连接
select concat_ws(',','1',null,'2'); 指定使用逗号进行分隔
执行结果:1,2
2、求和:SUM()
sum 求和时会对 null 进行过滤,不计算
select sum(age) from user;
执行结果:66
注意:如果在没有返回行中使用 sum() 函数,sum 函数的返回值为 null,不是 0,这个时候方法接收用int会直接报错,解决办法如下
select sum(age) from user where age > 50;
执行结果:NULL
解决:使用以下两个函数进行结果的转换
select ifnull(sum(age),0) from user where age > 50;
select coalesce(sum(age),0) from user where age > 50;
执行结果:0
3、统计行数:COUNT()
COUNT(*)和COUNT(1) 会统计表中的所有的记录数,包含字段为null 的记录
select count(*) from user;
执行结果:4
select count(1) from user;
执行结果:4
COUNT(字段) 会统计该字段在表中出现的次数,忽略字段为null 的情况。即不统
计字段为null 的记录
select count(age) from user;
执行结果:3