DQL:数据查询语句
1.基础查询
1.语法:
select 字段列表
from 表名1,表名2
where 条件列表
group by 分组字段
having 分组之后的条件
order by 排序
limit 分页限定
2.基础查询操作:
1.多个字段的查询
select age,stuname from stu1; -- 查询姓名和年龄
2.去除重复
select distinct addr from stu1;-- 去除重复的结果集
3.计算列
-- 计算math和english分数之和,如果有null,计算结果都为null。
select stuname,math,english,math+stu1.english from stu1;
select stuname,math,ifnull(english,0),math+ifnull(english,0) from stu1; 解决办法
由于null参与的运算,结果都为null 出现了: – ifnull(表达式1,表达式2); 表达式1:哪个字段需要判断是否为null。 表达式2:null的替换值
4.起别名
--别名 as可省略
select stuname,math,ifnull(english,0),math+ifnull(english,0) as 总分 from stu1;
2.排序查询:
*语法:order by 子句
select * from 数据库名 order by 排序字段 排序方式1,排序字段2 排序方式2 ;
*ASC: 升序,默认 ; DESC: 降序。
select * from stu1 order by math desc ; --按照数学成绩降序排序
--安装数学成绩降序排序,如果数学成绩相同,按照英语成绩升序
select * from stu1 order by math desc ,english ASC ;
3.条件查询:
1.where子句后跟条件
2.运算符: * > , < , <= ,>=,=,<>
select * from stu1 where age !=22 ; -- 查询年龄不等于22岁
select * from stu1 where age <>22 ; -- 查询年龄不等于22岁
*between…and
select * from stu1 where age>=20 && age<=30; -- 查询年龄大于20,小于30
select * from stu1 where age<=20 and age<=30; -- 查询年龄大于20,小于30
select * from stu1 where age between 20 and 30; -- 查询年龄大于20,小于30
*in(集合)
select * from stu1 where age in(18,19); -- 查询年龄为18岁,19岁的信息
*like:模糊查询
*占位符: “ _ ”:单个任意字符 。“%” :“多个任意字符”
select * from stu1 where stuname like 'J%'; -- 查询第一个字符为J的信息
select * from stu1 where stuname like '%o%'; -- 查询名字中有o 的信息
select * from stu1 where stuname like '___'; -- 查询名字为三个字符的信息
*is null
select * from stu1 where english=null; – 错误写法,null值不能使用 = 或!= 判断。
-- 查询英语成绩为null的信息
select * from stu1 where english is null;
*and 或 &&
*or 或 | |
-- 查询年龄为18岁,19岁的信息
select * from stu1 where age =18 or age=19 ;
*not 或 |
4.聚合函数:
将一列数据作为一个整体,进行纵向的计算。(不包含null值)
1.count:计算个数
select count(stuname) from stu1;
--计算stu1数据库中 stuname的元素个数
select count(ifnull(stuname,0)) from stu1;
--如果stuname这一列有null值,替换为0
select count(id) from stu1; --一般选择非空的列(主键)
2.max:计算最大值
select max(math) from stu1;
3.min:计算最小值
4.sum:计算和
5.avg:计算均值
5.分组查询:
1.语法:group by 分组字段
注意:1.分组之后查询的字段:分组字段,聚合函数。(参考select后的sex)
2.where和having的区别?
1.where在分组之前限定,如果不满足条件,则不参与分组。
having在分组之后限定,如果不满足结果,则不会被查询出来。
2.where后不可以跟聚合函数,而having可以进行聚合函数的判断。
-- 按照性别分组,分别查询男同学,女同学的平均分
select sex,avg(math)from stu1 group by sex;
-- 按照性别分组,分别查询男同学,女同学的平均分和各自的总人数
select sex,avg(math) ,count (id) from stu1 group by sex; -
-- 按照性别分组,分别查询男同学,女同学的平均分(如果math分低于等于70不参与查询)和各自的人数
select sex,avg(math) ,count (id) from stu1 where math>70 group by sex;
-- 按照性别分组,分别查询男同学,女同学的平均分(如果math分低于等于70不参与查询)和各自的人数
select sex,avg(math) ,count (id) from stu1 where math>70 group by sex having count(id)>2;
6.分页查询:
1.语法:“ limit 开始的索引,每页查询的条数;”
-- 每页显示两条记录。
select * from stu1 limit 0,2; -- 第一页
select * from stu1 limit 2,2; -- 第二页
--公式: 开始的索引=(当前的页码-1)*(每页显示的条数)
分页操作中limit是mysql的“方言”。