天天看点

Sqlserver 中 CrossApply 和 inner join 的区别

Cross Apply和Inner Join 有很多相同处,都是为了联表查询数据,而且取两张表之间的交集,不同在于,Cross apply 可以在 右表中加入左表的字段作为条件。

一:应用场景:

可见表中每一个产品(pro_id)可能对应多个图片(img),我想要按照添加时间的先后顺序,获得其中每一个产品的第一张图片

select * from Product
select * from product_imgs
           
Sqlserver 中 CrossApply 和 inner join 的区别

二:使用 inner join 和 partition by

select a.id,a.title,t.* from Product as a
inner join 
(select * from (select  b.pro_id,b.img,ROW_NUMBER() over(partition by pro_id  order by create_time)  as rank_col from product_imgs as b )
as T
where T.rank_col=1) as t on a.id=t.pro_id
           
Sqlserver 中 CrossApply 和 inner join 的区别

三:使用Cross Apply

select a.id,a.title,t.* from Product as a
cross apply 
(select top 1 b.pro_id,b.img  from product_imgs as b where b.pro_id=a.id)
as t 
           
Sqlserver 中 CrossApply 和 inner join 的区别

总结:inner join 和 cross apply 应用场景有相同也有不同之处