❓ DQL数据库查询⭐️⭐️⭐️
⭐️查询
sql的执行顺序
全字段查询
select 字段名,字段名,字段名,字段名 from student;
❌select * from student (不推荐,会影响性能)
1️⃣局部查询
❓所有查询出来的数据,是不是一张表?
所有的查询都会得到一张虚拟的表 ❗,查过的表再也不会改变 ❗
-- 正常的对字段的别名
select sname as '姓名' from user
-- 对字段的别名,有三种格式
select sname as '姓名', birthday '生日', sex 生日 from user
2️⃣添加字段
select name, ‘援救’ 学校 from student
⭐️⭐️ ⭐️distinct去重
所有指定的字段的数据一致的情况才会进行去重
select distinct seex from student
3️⃣带条件的查询
select name from where sid = 5;
select name from where sid <>5;
select name from where sid >5;
select name from where sid <10;
select sname from where ssex = '女' and classid = 1
select sname 姓名 from student where ssex = '女' and classid = 1
select sname from student where birthday < '1990-1-1';
⭐️入职时间,日期的比较,逻辑都是倒着的!找出比1998-4-9年龄大于她的人?
select sname from student where birthday < '1998-4-9';
4️⃣in在某个特定范围内,不使用or
因为or会让索引失效!
-- 删选sid等于1 3 5 7 9的所有学生!
select * from student
where sid in (1,3,5,7,9);
5️⃣Like模糊查询
- 模糊符号
- %:表示任意多的任意字符
- _(下划线):单个字进行匹配查询
select * from user where user_name Like '杨_'
select * from user where user_name like '%杨'
6️⃣null的查询 is关键词
select * from user where birthday is null
select * from user where birthday is not null
✅7️⃣ 聚合函数(🔥把多个值变为一个值🔥)
count():统计个数 🌹不统计NULL
学生表中有多少人?
select count(字段/常量/*号) from user
select count(id) from user; -- 主键
//统计某个字段
select count(1) from user; -- 推荐使用,数字随便填写
select count(*) from user; -- 推荐使用
max():求最大值
min():求最小值
sun():求总和
avg():求平均值
8️⃣Group by分组
-- 查询每个班同学的个数
select classid, count(*) from student group by classid
9️⃣having进行分组之后进行筛选
分组之后进行筛选
select sid"主键", sum(score) "总分", avg(score) "平均分" from sc group by sid having avg(score) < 60
✔面试题havimg和where的区别?
having是针对使用聚合函数的,而where是针对使用单个数据的。
1️⃣0️⃣Order By排序
-
asc 升序(默认)
-
desc 降序 (必须声明)
-
先写先排,有相同的以此类推进行排序
select * from student order by classid asc ;
1️⃣1️⃣ limit分页
limit分页,从0 开始 (页码-1)*步长,步长,应用层解决
select * from student limit 6,3;
例子:成绩及格的总分数排名第二的学生的sid和总成绩
select sid "id", sum(score) "总成绩" from sc group by sid having min(score) > 60 limit 1,1