简体   繁体   中英

How to get last children records with parent record from database

I have database with two tables: Customers (Id PK, LastName) and Orders (Id PK, CustomerId FK, ProductName, Price, etc.)

I want to retrieve only customer' last orders details together with customer name. I use .NET L2SQL but I think it's SQL question more than LINQ question so I post here SQL query I tried:

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]

Problem is that Orders has more columns (30) and with each column the query gets bigger and slower because I need to add next subqueries.

Is there any better way?

In SQL Server 2005 and above:

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

or this:

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

In 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
        )

Don't you have a date of column in the orders table something like order_date? Instead of select top you should be able to retrieve using max(order_date)

My sql is rusty but something like this

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM