cross apply 与 inner join 的区别

本文通过一个SQL查询实例,详细解析了内连接(INNER JOIN)与外连接(LEFT JOIN)的区别,并展示了如何在实际应用中使用crossapply和outerapply。同时,探讨了如何利用CTE(公共表表达式)优化大数据量查询效率。

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

下面还有一个小例子,根据小例子可以将cross apply /outer apply 分别换成inner join /left join,结果是一样的,但是cross apply之后一般是带函数.
inner join之后一般是带表.

create table #T(姓名 varchar(10))
insert into #T values('张三')
insert into #T values('李四')
insert into #T values(NULL )
 
 
create table #T2(姓名 varchar(10) , 课程 varchar(10) , 分数 int)
insert into #T2 values('张三' '语文' , 74)
insert into #T2 values('张三' '数学' , 83)
insert into #T2 values('张三' '物理' , 93)
insert into #T2 values(NULL '数学' , 50)
 
--drop table #t,#T2
go
 
select 
    
from 
    #T a
cross apply
    (select 课程,分数 from #t2 where 姓名=a.姓名) b

/*
select a.*,b.课程,b.分数
from 
    #T a
inner join#t2 b
where a.姓名=b.姓名

*/
 
/*
姓名         课程         分数
---------- ---------- -----------
张三         语文         74
张三         数学         83
张三         物理         93
 
(3 行受影响)
 
*/
 
select 
    
from 
    #T a
outer apply
    (select 课程,分数 from #t2 where 姓名=a.姓名) b

/*
select a.*,b.课程,b.分数
from 
    #T a
left join#t2 b
where a.姓名=b.姓名

*/

/*
姓名         课程         分数
---------- ---------- -----------
张三         语文         74
张三         数学         83
张三         物理         93
李四         NULL       NULL
NULL       NULL       NULL
 
(5 行受影响)

正好在查询cross apply与outer apply 区别的时候,同事看到了,然后就给了我下面的例子,解开了我之前的面试之谜。。。
(当时我用row_number,墨迹半天还觉得不对。。今天终于解决了)

选出每个source 的前100条数据!!
with b as (select distinct source from aqua_rpt.crd.crd_report_sft_derv_data) 
select * from b 
cross apply 

(select top 100 * from aqua_rpt.crd.crd_report_sft_derv_data a where b.source = a.source) a


当然也可以用下面的语句,但是由于 b表数据量很大,所以考虑到消耗内存太大,就采用 CTE.

select b.source,a.*

from aqua_rpt.crd.crd_report_sft_derv_data b

cross apply 

(select top 100 * from aqua_rpt.crd.crd_report_sft_derv_data a where b.source = a.source) a



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值