这是一些用于选择所有订单详细信息的 LINQ。它创建与产品表的连接以获取产品名称:
var query = from od in db.Order_Details
join p in db.Products on od.ProductID equals p.ProductID
select new { od.OrderID, od.ProductID, p.ProductName };
如果我不知道 Join 存在,我会这样做:
var query = from od in db.Order_Details
select new { od.OrderID,
od.ProductID,
ProductName = (from p in db.Products
where p.ProductID == od.ProductID
select p.ProductName).First()
};
它们生成不同的底层 SQL 代码。第一种方法是否比第二种方法快,如果是,为什么?
预计到达时间:
db.Log 用于连接查询:
SELECT [t0].[OrderID], [t0].[ProductID], [t1].[ProductName]
FROM [dbo].[Order Details] AS [t0]
INNER JOIN [dbo].[Products] AS [t1] ON [t0].[ProductID] = [t1].[ProductID]
db.Log 用于第二个查询:
SELECT [t0].[OrderID], [t0].[ProductID], (
SELECT TOP (1) [t1].[ProductName]
FROM [dbo].[Products] AS [t1]
WHERE [t1].[ProductID] = [t0].[ProductID]
) AS [ProductName]
FROM [dbo].[Order Details] AS [t0]