user485498
user485498

Reputation:

SQL combine two queries into one

These are simplified versions of three tables I have:

Books
BookID (PK)
AuthorID
...


Purchases
PurchaseID (PK)
CustomerID
BookID
Date
...

Authors 
AuthorID (PK)
Name
...

I'm hoping the connection between the tables is self explanatory, but I'll give a brief explanation: There is a one to many relationship between authors and books and between books and purchases.

Now I want to select a book from Books that are written by a given author and have been purchased more than X times.

I can query books for a given author:

SELECT * FROM Books where AuthorID = 'some author';

But I only want those books which have been purchased more than X times.

   SELECT BookID from Purchases WHERE ...(where the occurance of BookID>X)

I do not know how to complete this query, or even if it is possible. And then I want to combine it with the first query, using an INNER JOIN, if possible.

I am willing to accept that the design is flawed. Perhaps Purchases table should simply have BookIDs as PK and have a field for number of purchases.

Upvotes: 0

Views: 157

Answers (3)

John Woo
John Woo

Reputation: 263693

LEFT JOIN will allow records to be shown even if they have not purchase yet. The value of totalSold will be 0.

SELECT  a.BookID,
        b.Name,
        COUNT(c.BookID) totalSold
FROM    Books a
        INNER JOIN Authors b
            ON a.authorID = b.AuthorID
        LEFT JOIN   Purcahses c 
            ON a.BookID = c.BookID
WHERE   b.Name = 'AuthorName'
GROUP   BY a.BookID, b.Name
HAVING  COUNT(c.BookID) >= x -- <<== where X is the number of purchase

To further gain more knowledge about joins, kindly visit the link below:

Upvotes: 2

a1ex07
a1ex07

Reputation: 37354

SELECT b.*, a.Name as author_name
FROM Books b
INNER JOIN Authors a ON (a.AuthorId = b.AuthorId)
INNER JOIN 
(
SELECT BookID
--if you also want to include number of purchases to resultset, 
-- uncomment the line below
-- ,count(1) as cnt
from Purchases 
GROUP BY BookID
HAVING count(1) > x
)c ON (c.BookID = b.BookID)

Upvotes: 1

Meisner
Meisner

Reputation: 785

SELECT * FROM
Books INNER JOIN Purchases USING (BookID) 
WHERE AuthorID = ? 
GROUP BY BookID 
HAVING COUNT(BookID) > ?;

Upvotes: 2

Related Questions