本文主要内容:DQL
DQL:查询表中的记录
1. 基本语法
* 格式: select * from 表名;
* 说明: 1. select后面写表的列表名,如果是*表示在结果集查询表中的所有列
2. select后面的列名部分,我们可以使用as为列名起别名,这个别名显示在结果集中
3. 如果要查询多个列,之间使用逗号分隔
* 实例: 1. select * from stundet; --> 最简单的查询全部
2. select name as a, age from student;
2. 消除重复行
* 格式: select distinct 列名 from 表名;
* 实例: select distinct gender from student;
3. 条件查询
1. 比较运算符
* 等于 =
* 大于 >
* 小于 <
* 大于等于 >=
* 小于等于 <=
* 不等于 !=
* 需求: 查询id大于2的所有用户数据
* 实例: select * from student where id>2;
2. 逻辑运算符
* 且 and
* 或 or
* 非 not
* 需求: 查询id大于5的女同学
* 实例: select * from student where id>5 and gender="女";
3. 模糊查询
* like
* % 表示任意多个任意字符
* _ 表示一个任意字符
* 需求: 查询姓习的同学
* 实例: select * from student where name like "习%",
4. 范围查询
* in 表示在一个非连续的范围内
* between..and.. 表示在一个连续的范围内
* 需求: 查询编号是6、8、10的学生
* 实例: select * from student where id in (6,8,10);
* 需求: 查询编号是6-8的学生
* 实例: select * from student where id between 6 and 8;
5. 空判断
* is null 判断空
* is not null 判断非空
* 注意: null与""是不同的
* 需求: 判断是否有地址为空的学生
* 实例: select * from student where address is null;
6. 优先级
* (), not, 比较运算符, 逻辑运算符
* 注意: and的优先级大于or
4. 排序查询
* 格式: select * from 表名 order by 列1 ASC|DESC, 列2 ASC|DESC...;
* 说明: 1. 将数据按照列1进行排序,如果某些列1的值相同,则按照列2进行排序.....
2. 默认按照从小到大进行排序
3. ASC升序, DESC降序
* 实例: select * from student order by age DESC;
5. 聚合函数: 将一列数据作为整体,进行纵向的计算
1. count(*): 表示计算中行数
* 格式: select count(*) from 表名;
* 需求: 查询学生总数
* 实例: select count(*) from student;
* 补充: 一般选择非空的列: 主键或count(*)
2. max(列): 查询此列的最大值
* 格式: select max(列) from 表;
* 需求: 查询女生编号最大值
* 实例: select max(id) from student where gender="女";
3. min(列): 查询此列的最小值
* 格式: select min(列) from 表;
* 需求: 查询女生年龄的最小值
* 实例: select min(age) from student where gender="女";
4. sum(列): 查询此列的和
* 格式: select sum(列) from 表名;
* 需求: 查询女生的年龄和
* 实例: select sum(age) from student where gender="女";
5. avg(列): 查询此列的平均值
* 格式: select avg(列) from 表名;
* 需求: 查询女生年龄的平均值
* 实例: select avg(age) frmo student where gender="女";
* 注意: 聚合函数的计算会排除NULL值
解决方法:
1. 选择不包含非空的列进行计算
2. IFNULL函数: select count(IFNULL(english, 0)) from student;//按英语成绩列查询,如果成绩为NULL,使用0代替
6. 分组查询: 按照字段分组,表示此字段相同的数据会被放到一个集合中
* 格式: select 列1, 列2, 聚合1,聚合2 from 表名 group by 列1, 列2, ...;
* 需求: 查询男女生总数
* 实例: select gender, count(id) from student group by gender;
* 需求: 查询男女生的平均分和人数,要求:分数低于70不参与分组,分组之后,人数需要大于2人
* 实例: select gender, avg(math), count(id) from student where math>70 group by gender having count(id)>2
* 注意:where和having的区别
1. where在分组之前进行限定,如果不满足条件,则不参与分组,having在分组之后进行限定, 如果不满足结果,则不会被查询
2. where后不可以跟聚合函数, having可以进行聚合函数的判断
7. 分页查询:
* 格式: select * from 表名 limit start, count;
* 说明: strat表示索引(从0开始)
* 补充: 开始的索引 = (当前的页码 - 1) * 每页显示的条数
* 实例: select * from student limit 0, 3; //第一页
select * from student limit 3, 3; //第二页