首页 > 数据库 >数据库(MySQL)-DQL数据查询语言

数据库(MySQL)-DQL数据查询语言

时间:2024-07-25 20:00:34浏览次数:15  
标签:classid sc score select student MySQL DQL 查询语言 SELECT

        DQL(Data Query Language 数据查询语言)的用途是查询数据库数据,如select语句。其中,可以根据表的结构和关系分为单表查询和多表联查。

单表查询

        单表查询:针对数据库中的一张数据表进行查询

全字段查询

        语法:select 字段名 from 表名

#推荐
select sid,sname,birthday,ssex,classid from student;
#不推荐,不利于SQL优化
SELECT * from student;

结果:

 部分字段查询

SELECT sname from student;

结果:

字段起名

        语法:select 旧字段名 as 新字段名,旧字段名 ‘新字段名’,..., 旧字段名 ‘新字段名’  from 表名

select sname as '姓名', birthday '生日' from student;

结果:

添加字段

        语法:select 旧字段名,...,旧字段名,‘新字段值’  新字段名 from 表名

SELECT sname,'猿究院' 学校 from student;

结果:

 

select sid,sname,birthday,ssex,classid,'猿究院' 学校 from student;

去重

使用distinct去重

        语法: select distinct 需要去重的值 from 表名

select distinct ssex from student;

结果:

        要注意的是,所有字段都相同时,distinct才去重。若有一个陈同学 男和陈同学 女,我们不应该将其视为去重对象:

select distinct sname,ssex from student;

结果:

使用group by去重

条件查询

        使用【where】条件子句进行查询。

单条件查询

        语法:select * from 表名 where 条件;

# 在student表中查询sid等于5的数据
select * from student where sid=5;
select * from student where sid<>5;

结果:

多条件查询

        使用"and" 和"or"来连接多个条件

#查找1班的女同学
select * from student where classid=1 and ssex='女';

结果:

         那我们想查找sid为3,6,9的学生信息呢?

SELECT * FROM student 
WHERE sid=3 OR sid=200 OR sid=6;

        也可以使用in关键字:

SELECT * FROM student 
WHERE sid in(3,6,9);

         结果:

 模糊查询

        模糊符号:① "%":匹配任意多个字符

                         ② ”_“:匹配任意一个字符

        首先我们先插入几条数据:

insert into student (sname)
values('卫小佳'),('小佳佳'),('卫公主'),('宇宙无敌美女佳佳'),('卫美女');

我们想查找关于‘卫小佳’的信息,就可以通过模糊查询进行查找:

SELECT *FROM student WHERE sname LIKE '%佳%'

 结果:

SELECT *FROM student WHERE sname LIKE '卫__';
SELECT *FROM student WHERE sname LIKE '卫%';

结果:

 查找null和非null值

关键字:is null

SELECT * FROM student WHERE birthday IS NULL;

结果:

关键字:is not null 

select * from student where birthday is not null;

结果:

常用聚合函数

1.count():统计个数

语法:select count(字段\常量\*) from 表名  

注意:count()方法不统计null

统计行数:

SELECT COUNT(sid) from student;
SELECT COUNT('a') from student; -- 不推荐
SELECT COUNT(1) from student;
SELECT COUNT(*) from student;

 2.max():求最大值
3.min():求最小值
4.sum():求和
5.avg():求平均

SELECT COUNT(score) from sc;
SELECT sum(score) from sc;
SELECT avg(score) from sc;
SELECT max(score) from sc;
SELECT min(score) from sc;

6.综合

案例1. 统计出一共有多少场考试,平均分,总成绩、最高分、最低分

select count(*),sum(score),avg(score),max(score),min(score) from sc;

结果:

 分组-group by

关键字:group by

案例1.

select ssex,count(*) from student group by ssex;

结果:

案例2.查询各班有多少人

select classid,count(*) from student group by classid;

结果:

案例3.查看成绩表中每个同学的总分和平均分

select sid,sum(score),avg(score) from sc group by sid;

运行结果:

案例4.统计平均分不及格的同学

SELECT sid,avg(score) FROM sc
WHERE avg(score)<60 GROUP BY sid;

         运行后发现报错:

        原因是:where语句是用来判断每一条子句的,后面不能跟聚合函数,我们可以使用having关键字来判断。

select sid,avg(score) from sc group by sid having avg(score)<60;

结果:

排序-order by

升序-asc

使用ASC关键字,也可以不写,默认为升序排序:

select * from sc order by score;
select * from sc order by score asc;

结果:

降序-desc

        使用dsc关键字进行降序排序,不可省略:

select * from sc order by score desc;

结果:

综合排序

        案例:先按score降序,若相同,再按cid升序排序

select * from sc score desc,cid asc;

结果:

分页-limit

        语法:select * from student limit 开始位置 步长,位置=页码-1*步长

SELECT * from student LIMIT 0,3

结果:

2.

SELECT * from student LIMIT 1,3

 结果:

3. 找到成绩及格的总分数排名第二的 sid总成绩

select sid,sum(score) from sc
group by sid
having sum(score)>60
order by sum(score) desc
limit 1,1;

结果:

多表联查

        多表联查:针对数据库中两张或两张以上的表同时进行查询

        多表联查可以通过连接运算,即将多张通过主外键关系关联在一起进行查询,以下五张表是我们的数据:

内联查询

 非等值查询

        非等值查询就是将两个表做了笛卡尔积运算,运行结果的逻辑时混乱的

SELECT * FROM student,class;

 

等值查询

        只有完全满足条件(主外键关系)的数据才能显示结果

案例1:查询出学生和班级的信息

select * from student,class
where student.classid=class.classid;

结果:

案例2: 5张表联查

select * from student,class,teacher,sc,course
where student.classid=class.classid and
course.Tid=teacher.Tid and 
course.Cid=sc.Cid and 
sc.Sid=student.sid;

结果:

案例3:查询学过张三老师课程的学生的学号姓名

select sid,sname from student,teacher,sc,course
where course.Tid=teacher.Tid and 
course.Cid=sc.Cid and 
sc.Sid=student.sid and
tname='张三';

结果:

案例4:查询每个学生的平均成绩

select sname,classname,avg(score) 'avg'
from student,class,sc
where student.classid=class.classid and student.Sid=sc.Sid
group by student.sid;

结果:

inner join on内联 

        关键字:inner join on 两表的关系

        内联查询适合于:表少但数据量大,内存占用小,io高

案例1:查询出学生和班级的信息

select * from student
inner join class on student.classid=class.classid;

结果:

 案例2:男同学的班级信息

SELECT * FROM student
INNER JOIN class on student.classid=class.classid
WHERE ssex='男';

结果:

案例3:五表联查

SELECT * FROM studen
INNER JOIN class on student.classid=class.classid
INNER JOIN sc on sc.Sid=student.sid
INNER JOIN course ON course.Cid=sc.Cid
INNER JOIN teacher on course.Tid=teacher.Tid;

结果:

案例4:查询每门课程的平均成绩 显示:课程名称 老师名称 平均成绩

SELECT Cname,Tname,avg(sc.score) from sc
inner JOIN course ON course.Cid=sc.Cid
INNER JOIN teacher on teacher.Tid=course.Tid
GROUP BY course.Cid;

结果:

外联查询

重点要找到主查表:student

LEFT JOIN ON 左外联

主表(student)在 jion的左边:

SELECT *FROM student
LEFT JOIN class on student.classid=class.classid;

结果:

 RIGHT JOIN ON 右外联

主表(student)在 jion的右边

SELECT *FROM class
RIGHT JOIN student on student.classid=class.classid;

结果:

综合

案例1:查询所有的学生都学过多少门课程

select sname,count(cname) '课程数' from student
left join sc on student.sid=sc.sid
LEFT JOIN course ON sc.cid=course.Cid
group by student.sid

结果:

案例2:查询没有班级的同学

SELECT * FROM student
LEFT JOIN class ON class.classid=student.classid
WHERE class.classid is null;

结果:

案例3:查询没有同学的班级

SELECT * FROM class
LEFT JOIN student on class.classid=student.classid
WHERE student.sid is not NULL;

结果:

并集-UNION

注意:UNION有去重机制(所有参数必须完全相同才会被去重)

案例1:查询所有人的名字

SELECT sname FROM student
UNION
SELECT tname FROM teacher

结果:

案例2:查询所有人的姓名和性别(在student表中,性别的类型是char,而在teacher表中,性别的类型是int,但是不同类型的字段可以合并)

SELECT sname,ssex FROM student
UNION
SELECT tname ,tsex FROM teacher

结果:

//不同列数量的结果集不可以合并:

SELECT sname,ssex,sid FROM student
UNION
SELECT tname ,tsex FROM teacher

结果:

//起别名给第一个结果集才有用:

SELECT sname 姓名,ssex 性别 FROM student
UNION
SELECT tname ,tsex FROM teacher

结果:

SELECT sname ,ssex  FROM student
UNION
SELECT tname 姓名,tsex 性别 FROM teacher 

结果:

案例3: 查询没有班级的同学和查询没有同学的班级

SELECT * FROM student
LEFT JOIN class ON class.classid=student.classid
WHERE class.classid is null
UNION
SELECT * FROM student
RIGHT JOIN  class on class.classid=student.classid
WHERE student.sid is not NULL;

结果:

全连接

去重

案例:要获取没有班级的同学、查询没有同学的班级还要既有班级又有同学的

SELECT * FROM student
LEFT JOIN class ON class.classid=student.classid
UNION
SELECT * FROM student
RIGHT JOIN  class on class.classid=student.classid

不去重

SELECT * FROM student
LEFT JOIN class ON class.classid=student.classid
UNION ALL
SELECT * FROM student
RIGHT JOIN  class on class.classid=student.classid

 

子连接

        子查询又叫内部查询,子查询必须放在小括号中,子查询的效率极低

1.WHERE子查询

案例1:找出最大id的学生信息

select * from student
where sid=(select max(sid) from student)

结果:(先执行子查询,查找出最大的id,根据最大i查出学生信息)

案例2:查询每个班id最大的学生

#子句:查询出每个最大的id
#select max(sid) from student group by classid

select * from student
where sid in(
select max(sid) from student group by classid
)

结果:

案例3:查询学过张三老师课程的学生

select * drom student where sid in(
    select sid from sc where cid=(
        select cid from course where tid=(
            select tid from teacher where tname='张三')))

结果:

案例4:查询没学过张三老师课程的学生

select * drom student where sid not in(
    select sid from sc where cid=(
        select cid from course where tid=(
            select tid from teacher where tname='张三')))

结果:

2.FROM子查询

案例1:查询人数大于5的班级 显示:班级 人数

方法1:不使用子查询

select classname count(*) from class
left join student on class.classid=student.classid
group by class.classid 
having count(*)>5

结果:

方法2:使用子查询

select classname,人数 from class 
left join
(select classid,count(*) 人数 from student
group by classid) t1 
on class.classid=t1.classid
where 人数>5 

结果:

3.EXISTS子查询

用法:子句有结果,父查询执行;子句没有结果,父查询不执行:

select * from teacher
where exists(SELECT * FROM student where classid=1)

子句有结果:

父查询执行:

4.ANY\SOME\ALL子查询

案例1:查询1班比2班最低成绩高的学生

方法1:使用子查询

//子查询先查询出2班的最低成绩
/*
SELECT min(score) from sc
LEFT JOIN student on sc.sid=student.Sid
where sc.cid=2;
*/
select student.* from sc
left join student on sc.sid=student.Sid
where student.classid=1 and score>(
    SELECT min(score) from sc
    LEFT JOIN student on sc.sid=student.Sid
    where sc.cid=2;
)

方法2:使用any

SELECT DISTINCT student.* FROM sc
LEFT JOIN student on sc.sid=student.Sid
WHERE student.classid=1 and score >any(
SELECT score from sc
	LEFT JOIN student on sc.sid=student.Sid
	where student.classid=2)

结果:

 案例2:查询1班比2班最高成绩高的学生

使用all关键字:

SELECT DISTINCT student.* FROM sc
LEFT JOIN student on sc.sid=student.Sid
WHERE student.classid=1 and score >all(
SELECT score from sc
	LEFT JOIN student on sc.sid=student.Sid
	where student.classid=2)

结果:

结果集的控制语句

1.IF(expr1,expr2,expr3)

参数:

-- expr1 条件
-- expr2 条件成立,显示数据
-- expr3 条件不成立,显示数据

//例如在teacher表中,性别是通过int类型表示的,当我们想让结果集按我们规定的:1代表女,0代表男来显示,就可以使用if控制语句:

select tid,tname,if(tsex=1,'女','男') 性别,tbirthday,taddress from teacher;

结果:

2.IFNULL(expr1,expr2)

参数:

-- expr1 字段
-- expr2 字段为null时显示的默认值

//查询student表中的数据,当birthday为null时显示"石头里蹦出来的":

select sidsname,ifnull(birthday,'石头里蹦出来的') 生日,ssex from student

结果:

3.CASE WHEN THEN END

这个语句类似于java中的switch语句,具体用法如下:

select tid,tname
case tsex
    when 0 then '男'
    when 1 then '女'
    else '保密'
END '性别' ,tbirthday FROM teacher

结果:

注意:这个语句自带break语句:

SELECT score,
CASE
 	when score>=90 THEN 'A'
	when score>=80 THEN 'B'
	when score>=70 THEN 'C'
	when score>=60 THEN 'D'
	when score <60 THEN '不及格'
end '等级' from sc;

结果:

案例1:统计各个分数段的人数

思路:通过CASE WHEN THEN END语句可以只显示出满足该成绩段的成绩,其余不显示:

SELECT
CASE WHEN score<=100 and score>=90 then score end '100-90',
CASE WHEN score<=90 and score>=70 then score end '90-70',
CASE WHEN score<=70 and score>=60 then score end '70-60',
CASE WHEN score<60 then score end '不及格'
from sc

结果:

然后可以直接通过count()统计每个分数段的行数(count不统计null值),得出的行数就是该分数段的人数:

SELECT  '人数' 分数段,
count(CASE WHEN score<=100 and score>=90 then score end)  '100-90',
count(CASE WHEN score<=90 and score>=70 then score end)  '90-70',
count(CASE WHEN score<=70 and score>=60 then score end) '70-60',
count(CASE WHEN score<60 then score end)  '不及格'
FROM sc

结果:

方法2:

SELECT '100-90' 分数段 ,count(score) 分数 FROM sc
WHERE score<=100 and score>=90
UNION
SELECT '90-70' 分数段 ,count(score) 分数 FROM sc
WHERE score<=90 and score>=70
UNION
SELECT '70-60' 分数段 ,count(score) 分数 FROM sc
WHERE score<=70 and score>=60
UNION
SELECT '不及格' 分数段 ,count(score) 分数 FROM sc
WHERE score<=100 and score<60

 结果:

标签:classid,sc,score,select,student,MySQL,DQL,查询语言,SELECT
From: https://blog.csdn.net/weixin_64975807/article/details/140602778

相关文章

  • 腾讯云 Debian12 安装MySQL8亲测可用
    今天刚好需要部署一台服务器,网上查了资料,折腾很久,还是很多问题,现在把我的安装过程以及遇到问题的解决方案记录下来,供大家借鉴!1、更新系统sudoaptupdate2、下载软件包wgethttps://repo.mysql.com/apt/debian/pool/mysql-apt-config/m/mysql-apt-config/mysql-apt-con......
  • mysql查询今天、昨天、本周、本月、上一月 、今年数据
    原文链接:https://www.cnblogs.com/cnsdhzzl/p/12724580.html--今天select*from表名whereto_days(时间字段名)=to_days(now());--昨天SELECT*FROM表名WHERETO_DAYS(NOW())-TO_DAYS(时间字段名)<=1--本周SELECT*FROM表名WHEREYEARWEEK(date_format......
  • 一文读懂MySQL数据表索引的类型、创建方法、维护要点
    引言索引是数据库中用于提高查询效率的重要机制。在数据库系统中,索引类似于书籍的目录,它可以帮助数据库系统快速地找到特定数据的位置,从而加快查询速度。通过合理地创建和管理索引,可以显著提升数据库的性能,提高数据检索的效率,降低系统的资源消耗。本文将详细介绍MySQL数据......
  • MySQL空闲会话超时之interactive_timeout 与wait_timeout
    背景描述在用MySQLClient链接MySQLServer进行操作的是偶,如果一段时间没有操作,可能会遇到以下错误:ERROR2006(HY000):MySQLserverhasgoneawayNoconnection.Tryingtoreconnect...或者ERROR2013(HY000):LostconnectiontoMySQLserverduringquery这个报错......
  • 最新nacos下载安装,版本号2.4.0,nacos持久化存储到本地mysql中,nacos配置登录账户密码
    官网:https://nacos.io/zh-cn/docs/quickstart/quick-start1.下载地址:https://github.com/alibaba/nacos/releases网络不好,很难下载。直接使用git克隆,然后自己编译,这是最快的了。克隆:gitclonehttps://github.com/alibaba/nacos.git然后到根目录中(我的:E:\Demos\nacos),执行cmd命令:mv......
  • 虚拟机环境下Rocky 9.4安装Mysql8并配置Dbeaver客户端
    环境:服务器操作系统:Rocky9.4数据库:mysql8.0.38客户端操作系统:windows10Dbeaver版本:24.1.3Rocky9.4安装镜像下载地址:https://mirrors.aliyun.com/rockylinux/9.4/isos/x86_64/Rocky-9.4-x86_64-dvd.isoDbeaver安装文件下载链接:https://dbeaver.io/files/dbeaver-c......
  • MySQL 学习笔记 进阶(存储引擎,索引上)
    存储引擎 存储引擎-MySQL体系结构连接层服务层引擎层存储层 存储引擎-简介简介:存储引擎就是存储数据、建立索引、更新/查询数据等技术的实现方式。存储引擎是基于表的,而不是基于库的,所以存储引擎也可被成为表类型。在创建表时,指定存储引擎CREATETABLE表名(......
  • 第九讲: MySQL为什么有时候会选错索引?
    第九讲:MySQL为什么有时候会选错索引?​ 前面我们介绍过索引,你已经知道了在MySQL中一张表其实是可以支持多个索引的。​ 但是,你写SQL语句的时候,并没有主动指定使用哪个索引。也就是说,使用哪个索引是由MySQL来确定的。不知道你有没有碰到过这种情况,一条本来可以执行得很快......
  • MySQL篇
    一、定位慢查询定位慢查询很简单,主要有以下方式:通过运维工具分析开启mysql慢日志在mysql的配置文件/etc/my.cnf中配置并开启慢日志功能#开启MySQL慢日志查询开关slow_query_log=1#设置慢日志的时间为2秒,SQL语句执行时间超过2秒,就会视为慢查询,记录慢查询日志long_quer......
  • mysql常用语法
    MySQL约束注释--单行注释/*多行注释*/#井号注释MySQL命令执行顺序FROM>ON>JOINWHERE>GROUPBY>HAVING+聚合函数>SELECT>ORDERBY>LIMIT数据库设计——DDLshowdatabases; --查看当前所有的数据库use[数据库名]; --打开指定的数据库showtab......