大家好,今天给大家分享下SQL Server相关知识,本教程内容全部由本人亲测有效才放出来,网友们可以自己在本地自行练习。写此教程的目的也是希望可以加深自己对数据库操作语句的理解,同时也帮助到初学者,这里主要以代码的形式帮助大家动手练习,全文没有过多言语,也是为了简化大家对文字阅读的繁琐,最后希望能帮助到大家,喜欢就点个赞+关注,欢迎一起学习交流!
--子查询是一个嵌套在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);