(十四)嵌套子查询
--子查询是一个嵌套在select、insert、update或delete语句或其他子查询中的查询。任何允许使用表达式的地方都可以使用子查询。子查询也称为内部查询或内部选择,而包含子查询的语句也成为外部查询或外部选择。
--查询班级信息,统计学生人数
select *,(select count(*) from studentB where cid=classes.id) as num from classes order by num;
--in,not in子查询示例:查询班级id大于小于的这些班级的学生信息
select * from studentB where cid in(select id from classes where id>2 and id<4);
--查询不是某班的学生信息
select * from studentB where cid not in (select id from classes where name='2班')
--in、not in后面的子句返回的结果必须是一列,这一列的结果将会作为查询条件对应前面的条件。如cid对应的子句的id
--exists 和not exists 子句查询示例
--查询存在班级id为某某的学生信息
select * from studentB where exists(select * from classes where id=studentB.cid and id=3);
--查询没有分配班级的学生信息
select * from studentB where not exists(select * from classes where id=studentB.cid);
--exists和not exists查询需要内部查询和外部查询进行一个关联的条件,如果没有这个条件将是查询到所有的信息。如id等于studentB.cid;
--some、any、all子句查询示例
--查询班级的学生年龄大于班级的学生的年龄的信息
select * from studentB where cid=5 and age>all(select age from studentB where cid=3);
select * from studentB where cid=5 and age>any(select age from studentB where cid=3);
select * from studentB where cid=5 and age>some(select age from student where cid=3);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了