数据库学习(八)

限制数据查询---limit关键字

一般情况下查询出来的数据是在符合条件的情况下,查询出的所有数据;

限制数据查询是在查询出的数据中限制查询结果的数量

指定初始位置(默认从第一条数据开始显示)

语法:select f1...... from table_name where 条件 limit row_count(显示的数据数量);
--》查询表中提成为空的的所有员工
select ename,comm from t_employee where comm is null limit 1;
查询表中提成为空的前三条员工数据
select ename,comm from t_employee where comm is null limit 3;
select ename,comm from t_employee where comm is null limit 20;
说明:条件查询出的数据是10条,limit限制的数量是20条,sql正常运行,会把10条数据全部显示

指定初始位置

语法:select f1...... from 条件 limit start,row_count;
说明:start表示初始位置,从0开始,0表示第一条数据,row_count表示显示数据的数量
--》查询表中,提成为空的员工,按照工资降序排列显示
select ename,comm,sal from t_employee where comm is null order by sal desc;

降序后,查看第2条到第六条数据
select * from t_employee where comm is null order by sal desc limit 1,6;
从下标为1的第二条数据,查询5条,也就是第二条到第六条数据

统计函数和分组数据查询

mysql数据库提供的统计函数有:

count() :实现统计表中数据的条数

avg()函数;试下计算字段平均值

sum()函数:实现计算字段值的总和

max()函数:实现查询字段值中的最大值

min()函数:实现查询字段值中的最小值

语法:select function(f) from table_name where 条件;
1.1 count()函数
a:count(*)可以实现对表中数据进行统计,不管是null值还是非null值,全部统计数量
b:count(field)可以实现对指定的字段的数据进行统计,在具体统计是会忽略null值
--》统计员工的人数
select count(*) number from t_employee;
select count(ename) from t_employee;
对表中,统计有奖金的员工人数
select count(comm) number from t_employee where not comm=0;
说明:count(filed)会忽略null值,where条件过滤掉0值



1.2avg()函数    --平均值
语法:avg(field)对指定的字段平均值进行计算,在具体统计时会忽略null值
--》计算有奖金提成的员工平均值
select avg(comm) average from t_employee ;


 1.3sum()函数
语法:sun(field)对指定字段计算总和,忽略null值
-->计算员工领取工资的总和
select sum(sal) sumvalue from t_employee;



1.4max()函数    min()函数
max(field)对指定字段计算最大值,忽略空值
min(field)对指定字段计算最小值,忽略空值

--》查询表中员工的最高工资和最低工资
select max(sal) maxval,min(sal) minsal from t_employee;

在使用count()函数、avg()函数、sum()函数、max()函数、min()函数
时,如果表中没有任何数据记录,count()函数会返回0,其他函数没有返回null

--》
create table m_test(
                    id int primary key auto_increment,
                    name varchar(10) not null,
                    address varchar(50) unique key);

select * from m_test;
select count(id) from m_test;//执行结果为0
select avg(id),sum(id),max(id),min(id) from m_test;执行结果为null




















发布了90 篇原创文章 · 获赞 37 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_25368751/article/details/102909069