整理数据库的基础语句

152 阅读2分钟

DQL-条件查询

select * from emp where age>=15 && age<=20;
select * from emp where age>=15 and age <=20;
select * from emp where between 15 and 20;//15 和20 不能反过来
select * from emp where age=18 or age=20; //或者
select * from emp where age in(18,10,30);//代表只要age满足其一就行
查询姓名为两个字的员工姓名 select * from emp where name like '_ _';// _代表匹配单个字符,%代表匹配任意个字符
查询身份证号最后一位是X的员工信息 select * from emp where idcard like '%X';

DQL-聚合函数

1.将一列数据作为整体,进行纵向计算
eg:1.统计数量
select count(*) from emp;
2.统计平均年龄
select avg(age) from emp;
3.select max(age) from emp;
4.select min(age) from emp;
5.统计西安地区的年龄之和 select sum(age) from emp where workaddress='西安';

DQL-分组查询

where 是在分组之前进行过滤,不满足where条件,不参与分组,而having是分组之后对结果进行过滤
where 不能对聚合函数进行判断,而having可以
eg:1.根据性别分组,统计男性和女性员工的数量
select count( * ) from emp group by gender;//这里代表了分组后的每组数量
select gender ,count( * ) from emp group by gender;
2.查询年龄小于45的员工,并根据工作地址分组,获取数量大于等于3的工作地址
select location from emp where age<45 group by location having count(*)>=3;
3.进行分组查询返回的一般是分组字段和聚合函数

排序查询

ASC代表升序,desc降序
eg:1.对年龄升序
select * from emp order by age asc;
2.先按年龄排序,若相同再按时间排序
select * from emp order by age asc, entrydate desc;

分页查询

1.起始索引从0开始,起始索引=(查询页码-1)*每页显示记录数
2.如果查询是第一页数据,起始索引可以省略,直接写 limit 10
eg:1.查询第一页员工数据,每页展示10条记录
select * from emp limit 0,10;
2.查询第二页员工数据,每页展示10条记录
select * from emp limit 10,10;
3.查询性别为男,且年龄在20-40之间以内前5个员工信息
select * from emp where gender='男' and age between 20 and 40 order order by age limit 5;