MYSQL入门与进阶(十二)

本文介绍了SQL中子查询的使用,特别是在查询条件中作为条件存在的场景。讲解了如何利用=、><、IN、NOT IN等运算符与子查询结合,查找特定条件的数据。例如,通过子查询找到与特定学生同一城市的所有学生信息,以及查询最低分学生的详细信息。还探讨了当子查询返回多行时如何使用IN、ANY、ALL等关键字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


在查询条件的位置作为条件存在

通过=引⼊的⼦查询,必须返回单个值。只能匹配⼀⾏。值是⼀个,但是可以组合
如果确保只有⼀⾏⼀列的返回值即值只有⼀个,那么可以= > < >= <= in not in也⾏
Eg:查找和谭明同⼀城市的学⽣信息
Eg2:查找最低分的所有学⽣信息
– 子查询:查询结果作为检索条件的比对值存在
– 查询和马钰一个城市的学生信息
select city from studentinfo where studentname=‘马钰’
select * from studentinfo where city=‘商丘’
– =匹配,必须保证子查询返回的值只有一行一列
select * from studentinfo where city=(select city from studentinfo where
studentname=‘马钰’)
– > < != in(可以有多行范围) not IN
– 查询最低分的学生信息
select min(exam) from exam
select * from exam where exam=45
select * from studentinfo where studentid=‘2011001011’
select * from studentinfo where studentid=(
select studentid from exam where exam=(
select min(exam) from exam ) )
IN 、ANY 、ALL 的⽐较运算符引⼊的列表上操作的⼦查询(可以返回多列)
如果返回值是多⾏的情况下:不能使⽤=> <这些,可以⽤in not in >anyall <all这些关键字

-- 查询最低分的学生信息:如果最低分只有一个人,那么可以=
 -- 如果是多个人,必须用in
 select min(exam) from exam
 select * from exam where exam=45
 select * from studentinfo where studentid in('2011001011','2011001003')
 select * from studentinfo where studentid in(
 select studentid from exam where exam=(
 select min(exam) from exam
 )
 )
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值