------------------程序做得再好,数据有问题照样是个死 !

子查询

--子查询:一个查询中包含着另外一个查询,使用()包含子查询
--两种子查询:
--独立子查询:子查询是一个可以独立运行的完整的查询.在执行的时候先执行子查询,再执行父查询
--查询 比 周治明 大的所有学员信息
select BornDate from Student where StudentName='周治明'
select * from Student where BornDate>(select BornDate from Student where StudentName='周治明')
--相关子查询:子查询中使用了父查询中的值
--查询参加了考试的学员信息
select distinct StudentNo from Result
select * from Student where StudentNo=(select distinct StudentNo from Result where StudentNo=Student.StudentNo)
--子查询的几种使用方式:
--1.使用子查询做为条件:与关系运算符一起使用。
select * from Student where BornDate>(select BornDate from Student where StudentName='周治明')
--子查询返回的值不止一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。
select * from Student where BornDate>(select BornDate from Student)
--如果子查询返回了多个值,那么就使用in--多行一列.
select * from Student where ClassId not in(select classid from Classes where ClassId>6)
--如果是多列数据: 只能使用EXISTS
select * from Student where ClassId in(select * from Classes where ClassId>6)
--2.使用子查询做为结果集
--分页:
--前5条记录
select top 5 * from Student
--第二页
select top 5 * from Student where StudentNo not in (select top 5 StudentNo from Student)
select top 5 * from Student where StudentNo not in (select top 10 StudentNo from Student)
--使用函数生成行号进行条件判断实现分页
--ROW_NUMBER()生成行号 over 指定在那一个字段上进行排序
select ROW_NUMBER() over(order by studentno),* from Student
--from虚拟结果集的查询语句:1.虚拟结果集需要有别名 2.行号也需要有别名
select * from (select ROW_NUMBER() over(order by studentno) as id,* from Student) as temp where temp.id>5 and temp.id<=10
--子查询做为列的值
select (select studentname from student where studentno=result.studentno) as name,StudentResult from Result

--查询二期班开设的课程
--首先得明确需要你查询什么样的信息,也就意味着你先确定查询的表。子查询中父查询整体而言是一个单表操作 当你发现做为条件的值没有的时候,就使用子查询相等查询操作,返回需要的值
select * from Subject where ClassId=(select ClassId from Classes where classname='二期班')

posted @ 2015-03-19 22:35  俊落笔如歌  阅读(188)  评论(0编辑  收藏  举报
           人的本事不是与生俱来的,不是你掌握了多少,而是当你面对一个未知问题的时候,你能用多少时间来掌握!       ---------俊落笔如歌