目录
先创建一个student表,里面写入一些信息
一、条件查询
- 使用where子句对表中的数据筛选,结果为true的行会出现在结果中
- 语法如下:
select * from 表名 where 条件;
1、比较运算符
- 等于:=
- 大于:>
- 大于等于:>=
- 小于:<
- 小于等于:<=
- 不等于:!=
- 或:<>
- 查询id小于3的学生
select * from students where id<3;
- 查询成绩不及格(<60分)的学生并只显示他的名字
select name from students where score<60;
- 查询姓名不是“张三”的学生
select * from students where name!='张三';
2、逻辑运算符
- and
- or
- not
- 查询id>1且成绩score>60的同学
select * from students where id>1 and score>60;
- 查询id>1或成绩score>60的同学
select * from students where id>1 or score>60;
3、模糊查询
- like
- %表示任意多个任意字符
- _表示一个任意字符
- 先向表中插入两个同姓的同学信息
- 查询姓张的同学
select * from students where name like '张%';
- 查询姓张且名字为两个字的同学
select * from students where name like '张_';
- 查询姓李和姓名中有“无”的同学
select * from students where name like '李%' or name like '%无%';
4、范围查询
- 间隔返回:in(1, 5)表示在一个非连续的范围内
- 连续范围:between 2 and 4 (表示在一个连续的范围内)
- 查询id是1或3或5的同学
select * from students where id in(1,3,5);
- 查询id从2到4的同学
select * from students where id between 2 and 4;
5、空判断
- 注意:null与' '是不同的(null占用空间,而''不占用空间)
- 判空:is null
- 判非空:is not null
先向表中插入几个只有名字和成绩的同学信息,制造NULL
- 显示所有id不为空的信息
select * from students where id is not null;
- 只删除null值
delete from students where id is null;
6、优先级
二、排序、限制和去重操作
1、排序
- 开序:asc (默认)
- 降序:desc
先向表中插入几个无序的id
- 将id按顺序从小到大排序(开序)
select * from students order by id asc;
- 将id按顺序从大到小排序(降序)
select * from students order by id desc;
注意:虽然对表中的数据进行了开序和降序的操作,但是没有真正的改变数据顺序,只是在显示时表中的顺序发生改变。
原来的顺序没有改变
2、限制
- start :表示从什么位置开始;count:表示获取多少条数据
select * from 表名 limit start,count;
- 只显示三条数据
select * from 表名 limit 3;
- 从第3条数据开始,获取三条数据
select * from 表名 limit 3,3;
3、去重
- distinct (不会修改本身的数据)
增加一些重复数据
- 去掉重复的数据
select distinct * from 表名;
- 指定字段去重
select distinct id from 表名;
- 去重后查看数据是否改变
原来的数据没有发生改变
三、聚合查询
为了快速得到统计数据,提供了5个聚合函数
- count(*):表示计算总行数,括号中写星与列名,结果是相同的
select count(*) from students;
查询学生总数
- max(列):表示此列的最大值
- min(列):表示此列的最小值
查询成绩大于60分同学的id最大值
select max(id) from students where score>60
- sum(列):表示此列的和
求所有同学成绩总和
select sum(score) from students;
- avg(列):表示此列的平均值
求所有同学成绩的平均值
select avg(score) from students;
四、分组查询
- 按照字段分组,表示此字段相同的数据会被放到一个组中
- 分组后,只能查询出相同的数据列,对于有差异的数据列无法出现在结果集中
- 可以对分组后的数据进行统计,做聚合运算
- 语法:
select 列1,列2,... from 表名 group by 列1,列2,...
- 分组后取id大于4的数据
select * from students group by id having id>4;
1、分组后的数据筛选
- 语法
select 列 1, 列 2,聚合... from 表名 group by 列 1, 列 2, 列 3... having 列 1,...聚合...
- having后面的条件运算符与where的相同
- 原来的数据
- where语句和having语句的对比
- where是对from后面指定的表进行数据筛选,属于对原始数据的筛选
- having是对group by的结果进行筛选