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

时间:2011-04-14 10:43:36

标签: 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]

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

还有更好的方法吗?

2 个答案:

答案 0 :(得分:6)

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

或者这个:

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

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
        )

答案 1 :(得分:-1)

订单表中的列日期是否与order_date类似?您应该能够使用max(order_date)

检索而不是选择顶部

我的sql生锈了但是像这样

select c.col1,o.col1,o.col2,o.col3 from Customers as c, Orders as o where c.id = o.customerid and max(o.order_date)