💖大家好,我是Cx_330是💥
🎐DQL
SELECT
字段列表FROM
表名列表WHERE
条件列表GROUP BY
分组字段HAVING
分组后条件ORDER BY
排序字段LIMIT
分页限定
🎑-- 先添加一些数据
-- 删除stu表
drop table if exists stu;
-- 创建stu表
CREATE TABLE stu (
id int, -- 编号
name varchar(20), -- 姓名
age int, -- 年龄
sex varchar(5), -- 性别
-- 添加数据
INSERT INTO stu(id,NAME,age,sex,address,math,english,hire_date)
VALUES
(1,'马运',55,'男','杭州',66,78,'1995-09-01'),
(2,'马花疼',45,'女','深圳',98,87,'1998-09-01'),
(3,'马斯克',55,'男','香港',56,77,'1999-09-02'),
(4,'柳白',20,'女','湖南',76,65,'1997-09-05'),
(5,'柳青',20,'男','湖南',86,NULL,'1998-09-01'),
(6,'刘德花',57,'男','香港',99,99,'1998-09-01'),
(7,'张学右',22,'女','香港',99,99,'1998-09-01'),
(8,'德玛西亚',18,'男','南京',56,65,'1994-09-02');
🧧基础查询
- 方便书写取 字段名称:age 表明为 t
查询多个字段:select age from t
去除重复记录:select distinct age from t
起别名 as (可以省略 中间至少一个空格) select age as 年龄 from t
🧧条件查询
select age from t where age >30
常用的条件运算符: <>不等于 between and 在...和... 之间 In(...) 在多个范围之间 like 模糊查询 熟练理解 _ % 的作用 and or !
🎢🎢🎢🎢🎢
姓马的名字: select * from t where name like '马%' 第二个是花的名字: select * from t where name like '_花%' 包含德的名字: select * from t where name like '%德%'
🧧排序查询
select * from t order by age;默认升序
select * from t order by age,score desc;当age一样时,才会进行score排序
🧧聚合函数
count(age)
max(age)
min(age)
sum(age)
avg(age)
select sum(seore) from t;
⚽null值不参与所有聚合函数的运算⚽
-
🎭查询男女生数学平均分
select sex,avg(math) from t group by sex;
-
🎭查询男同学和女同学各自的数学平均分,以及各自人数,要求:分数低于70分的不参与分组,分组之后人数大于2个的
select sex,avg(math),count(*) from t where math>70 group by sex having (count*)>2;
👕 where和having区别
- 执行时机不同:where在分组前,having在分组后
- 可判断条件不同:where不能判断聚合函数,having可以,因为执行时机不同
🧧分页查询
select age from t limit 起始索引(0开始) , 查询条目数
🎡起始索引 = (当前页码 - 1) * 每页显示的条数