When should I use cross apply over inner join?

前端 未结 14 1066
忘了有多久
忘了有多久 2020-11-22 06:51

What is the main purpose of using CROSS APPLY?

I have read (vaguely, through posts on the Internet) that cross apply can be more efficient when selectin

14条回答
  •  旧巷少年郎
    2020-11-22 07:26

    This has already been answered very well technically, but let me give a concrete example of how it's extremely useful:

    Lets say you have two tables, Customer and Order. Customers have many Orders.

    I want to create a view that gives me details about customers, and the most recent order they've made. With just JOINS, this would require some self-joins and aggregation which isn't pretty. But with Cross Apply, its super easy:

    SELECT *
    FROM Customer
    CROSS APPLY (
      SELECT TOP 1 *
      FROM Order
      WHERE Order.CustomerId = Customer.CustomerId
      ORDER BY OrderDate DESC
    ) T
    

提交回复
热议问题