MYSQL简单查询
MYSQL简单查询
完整语法: select [distinct] , … [from [where ] [group by , … [having ] ] [order by asc| desc ] [limit [offset , ] rows ] ]
- select 简单查询
select 1 ; -- 往往用来 做 数据库心跳检测 select user() ; -- 获取 当前登录的用户信息 select version() ; -- 获取数据库的版本号 select now() ; -- 获取 当前系统时间 select last_insert_id() ; -- 获取 最后插入的主键(必须是自增)
- 基于 表查询
select <columnName> , .... from <tableName> ; select * from <tableName> ; -- 查询 表中所有的字段 , 在生产环境中 不推荐使用 * 查询所有字段
- 基于条件的查询
select <columnName> , ... from <tableName> where <condition> ; select * from tb_user where name = 'admin' ; -- 查询的时候 name的值 不区分大小写 select * from tb_user where binary name = 'admin' ; -- 查询的 name 值 区分大小写
- 基于分组的查询
- count() : 用来 统计 个数
-- 查询 学生表中 有多少个 学生 select count(*) from student ; -- 以行为单位 ,统计有多少个学生 select count(stuNo) from student ; -- 根据学号 来统计 有多少个学生 select count(1) from student ; -- 根据常量值 进行统计、如果有值,个数 + 1
从性能上 、 count(1 ) > count( * ), count(column) 只统计该列中 值不为 null 的 行数(null不参与统计) 。
如果 count(column) 中的 column 中的列 有索引,那么性能 会 比 count(1) 高 、 如果没有索引,性能 比 count(*) 还低
- sum() : 求和
-- 查询学生的总成绩 select sum(score) from student ; -- sum 函数 参数 只能传入 字段名, 字段列中对应的 null 不参与 求和
- avg() : 求平均值
-- 查询学生 的平均成绩 select avg(score) from student ; -- sum 函数 参数 只能传入 字段名, 字段列中对应的 null 不参与 求平均值 select avg ( ifnull(score, 0) ) from student ; -- 字段列对应的 null, 则 取 0 , 仍旧参与 求 平均值
- max() : 求最大值
-- 查询 最高分 select max(score) from student ;
- min() : 求最小值
-- 查询 最低分 select min(score) from student ; -- 空值不参与 求 最小值
- count() : 用来 统计 个数
- group by 实现 分组查询
-- 查询 不同 性别的 学生人数 select sex, count(1) from student group by sex ;
group by 分组 对查询的 列 有 要求 , 要么 查询的 列 是一个 聚合 列 、要么 出现 在 group by 的 后面,作为分组依据。
-
having 分组 筛选
对分组后的结果 进行过滤 、筛选, having 是 基于 group by 存在 的。
-- 查询 班级中 同名 、同性别 的 学生名 和 性别 select name, gender from student group by name ,gender having count(1) > 1 ;
where 和 having 的区别
- where 是 对 表中的 数据 进行筛选 , having 是 对 分组后的 结果 进行 筛选 。
- where 和 having 如果 同时 存在 ,那么 where 先筛选 再分组 再过滤
- where 条件 中 不能使用 聚合函数 、但 having 可以使用 聚合函数
- 能用 where 筛选过滤的数据 、尽量不要用 having 筛选
-
数据排序 order by
-- 查询 所有的学生信息 、按照 成绩降序排列,当成绩相同的时候 ,按照 出生日期 降序排列 select * from student order by score desc , birth desc ;
当 有多个字段 参与排序的时候, 优先根据 第一个排序的字段 进行排序,当 第一个字段 的值 相同的时候,才会根据第二个字段的值进行排序、依此类推。
-
分页查询 limit
select * from student limit 3 ; -- 查询表中 前 3 条数据 select * from student limit 10 , 3 ; -- 查询表中 从 第 11条数据开始 3 条数据 select * from student limit 10 offset 3 ;
分页查询的时候, 如果 包含 order by , 那么 建议根据 唯一键 进行排序 、如果 根据 的字段值有大量的重复、建议 使用 多个字段排序 , 否则 会出现 分页数据紊乱 。