如何使用数据库中的父记录获取最后一个子记录

jlp*_*jlp 3 sql database linq-to-sql

我有两个表的数据库: Customers (Id PK, LastName)Orders (Id PK, CustomerId FK, ProductName, Price, etc.)

我想只检索客户的最后订单详细信息以及客户名称.我使用.NET L2SQL,但我认为这是SQL问题而不是LINQ问题,所以我在这里发布我试过的SQL查询:

SELECT [t0].[LastName], (
    SELECT [t2].[ProductName]
    FROM (
        SELECT TOP (1) [t1].[ProductName]
        FROM [Orders] AS [t1]
        WHERE [t1].[CustomerId] = [t0].[Id]
        ORDER BY [t1].[Id] DESC
        ) AS [t2]
    ) AS [ProductName], (
    SELECT [t4].[Price]
    FROM (
        SELECT TOP (1) [t3].[Price]
        FROM [Orders] AS [t3]
        WHERE [t3].[CustomerId] = [t0].[Id]
        ORDER BY [t3].[Id] DESC
        ) AS [t4]
    ) AS [Price]
FROM [Customers] AS [t0]
Run Code Online (Sandbox Code Playgroud)

问题是Orders有更多的列(30),每列的查询变得越来越大,因为我需要添加下一个子查询.

有没有更好的方法?

Qua*_*noi 7

SQL Server 2005与上述:

SELECT  *
FROM    (
        SELECT  o.*,
                ROW_NUMBER() OVER (PARTITION BY c.id ORDER BY o.id DESC) rn
        FROM    customers c
        LEFT JOIN
                orders o
        ON      o.customerId = c.id
        ) q
WHERE   rn = 1
Run Code Online (Sandbox Code Playgroud)

或这个:

SELECT  *
FROM    customers c
OUTER APPLY
        (
        SELECT  TOP 1 *
        FROM    orders o
        WHERE   o.customerId = c.id
        ORDER BY
                o.id DESC
        ) o
Run Code Online (Sandbox Code Playgroud)

SQL Server 2000:

SELECT  *
FROM    customers ?
LEFT JOIN
        orders o
ON      o.id = 
        (
        SELECT  TOP 1 id
        FROM    orders oi
        WHERE   oi.customerId = c.id
        ORDER BY
                oi.id DESC
        )
Run Code Online (Sandbox Code Playgroud)