黑马视频-子查询

本文详细介绍了SQL中的子查询使用方法,包括独立子查询和相关子查询的应用场景,并提供了多个实例来展示如何使用子查询进行复杂的数据筛选和处理。
子查询:独立子查询 相关子查询
select * from (select col1,col2 from Tbl) as Tb

1、一个查询结果作为另一个查询的数据源 ,必须将子查询数据源 别名 as Tbs

select * from (select  
                    fname ,fage,fgender 
                from
                     MyStudent 
                where fage between 18 and 25 and fgender='女') as Tbs
where  fname like '%赵'

2、作为列

select 最高分= select max(score)  from Tbs,
        最低分=select min(score) from Tbs,
        平均分=select avg(score) from Tbs

3、将查询结果作为查询条件 

select   
             *
 from 
            TblStudent 
where 
    tsclassid=(select tsclassid form TblClass where className ='高二二班')

4、子查询只能返回单个值 
select * from Tbls where classId in  (select classId from Tbs where classId='4' or classId='5')
5、exists中包含的查询查到了结果则exists返回true,否则为false
if(exists(select * from Tbl where 1<>1))
begin
    print '有结果'
end
else
begin
     print '无结果'
end

select  *  from  Tbl where exists(
     select * from Tbl1 where name='高二二班' and Tbl.classId=Tbl1.classId
)

select * ,row_number() over (order by fid desc) as number from tb

20页,每页5条
select * from (
    select *,row_number() over (order by fid dsc ) as number from Tb
)
as TbNew where tbNew.number between 19*5+1 and 20*5

row_number()     行号 

select * ,count(*) from Tbl (错误)
select * ,count(*)  over () as 总条数 from Tbl 


















转载于:https://www.cnblogs.com/wupd2014/p/4965011.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值