Here’s some LINQ to select all order details. It creates a join with the product table to get the product name:
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 };
Here’s how I would do it if I didn’t know that Join existed:
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()
};
They generate different underlying SQL code. Is the first method faster than the second, and if so why?
ETA:
db.Log for join query:
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 for 2nd query:
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]
Joins are typically faster than equivalent nested selects since DBMS’ are very good at optimizing joins, although a good SQL compiler might optimize them to the same SQL anyway. You should use the one which makes your purpose more clear, which is probably the join in this case.