我有两个表的数据库:
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),每个列的查询变得越来越大,因为我需要添加下一个子查询。
还有更好的方法吗?
答案 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)