• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 51
  • Last Modified:

SQL Question for Inner join

Select * from OrderDetails inner join Products on Products.ProductID = OrderDetails.ProductID inner join Discounts on OrderDetails.DiscountID = Discounts.DiscountID where OrderID = 213

Open in new window

I'm trying to pull all the OrderDetails records where OrderID = 213.
Some OrderDetails records have Discounts (and a Discount ID)
If no discount has been applied to the OrderDetails, the value for DiscountID is Null.

I need to pull OrderDetails for ALL records for OrderID 213 - even those with a NULL value for DiscountID.

I would appreciate any help sorting out this query.  right now it's returning 1 record, it should return 6.

Thanks for your help!!!

3 Solutions
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
>Some OrderDetails records have Discounts (and a Discount ID)
<Knee-jerk reaction> Change the INNER JOINs to a LEFT JOIN, which will return all OrderDetails rows regardless of whether there is a related Discount row or not.
FROM OrderDetails 
   LEFT JOIN Products on Products.ProductID = OrderDetails.ProductID 
   LEFT JOIN Discounts on OrderDetails.DiscountID = Discounts.DiscountID 
WHERE OrderID = 213

Open in new window

Jose TorresSenior SQL Server DBACommented:
I think the LEFT JOIN should only exists between OrderDetails and Discounts
Then again this is assuming that OrderDetails.ProductID has a FK to Products.ProductID, then you may need a LEFT JOIN on both
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
^^^ Jose is very likely correct.  Since we can't access this data source and run queries, you'll have to run it yourself and verify.
Scott PletcherSenior DBACommented:
Select OD.*, P.*, D.*
from dbo.OrderDetails OD
inner join dbo.Products P on P.ProductID = OD.ProductID
left outer join dbo.Discounts D on OD.DiscountID = D.DiscountID
where OD.OrderID = 213
slightlyoffAuthor Commented:
Thanks for your help - I apologize for the delay in responding.
The SQL I ended up using was:  sql = "SELECT * FROM OrderDetails od full outer join products p on p.ProductID = od.ProductID full outer join Discounts d on od.DiscountID = d.DiscountID WHERE od.OrderID = " & theOrderID
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now