Wednesday, March 21, 2012

Help with a SQL query

I'm trying to draft a SQL Query for the following:
A bookstore that sells books - when a user selects a book to view it's
details, he should see a section that says "People who bought this book also
bought...with a list of various titles" - this is a common feature of sites
such as Barnes & Noble and Amazon.
How does the SQL Query work to get this information extracted out of the
database.
I have a Products table (with fields related to each product - Product ID,
Product Title, Product Category)
I have an Orders table (with fields related to each order - Order ID,
Persons ID, ...)
I have an Order Details table (with fields related to each item in the
order - Order ID, Product ID)RB wrote:
> I'm trying to draft a SQL Query for the following:
> A bookstore that sells books - when a user selects a book to view it's
> details, he should see a section that says "People who bought this book also
> bought...with a list of various titles" - this is a common feature of sites
> such as Barnes & Noble and Amazon.
> How does the SQL Query work to get this information extracted out of the
> database.
> I have a Products table (with fields related to each product - Product ID,
> Product Title, Product Category)
> I have an Orders table (with fields related to each order - Order ID,
> Persons ID, ...)
> I have an Order Details table (with fields related to each item in the
> order - Order ID, Product ID)
>
Assuming that you have the productID from the webpage, which will be
represented as @.PRODUCTID.
select P.productID, P.title
from Products P, OrderDetails OD
where P.productID = OD.productID and OD.PersonID IN (
select O.personID
from OrderDetails OD, Orders O
where OD.productID = @.PRODUCTID AND OD.OrderID = O.OrderID
)
Without the exact DB schema this is the best I could come up.
You will need to tweak it a little because you will get repeats etc.
It should be straight forward.

No comments:

Post a Comment