SQL将两个查询合并为一个

时间:2013-02-09 15:58:51

标签: sql

这些是我拥有的三个表的简化版本:

Books
BookID (PK)
AuthorID
...


Purchases
PurchaseID (PK)
CustomerID
BookID
Date
...

Authors 
AuthorID (PK)
Name
...

我希望表格之间的联系是自我解释的,但我会给出一个简短的解释:作者和书籍之间以及书籍和购买之间存在一对多的关系。

现在,我想从一本书中选择一本书,这本书是由一位特定作者撰写的,并且购买的次数超过X次。

我可以查询给定作者的书籍:

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

但我只想要购买超过X次的书籍。

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

我不知道如何完成此查询,或者即使可能。然后我想将它与第一个查询结合起来,如果可能的话使用INNER JOIN。

我愿意接受设计存在缺陷。也许购买表应该只有BookIDs作为PK,并有一个购买数量的字段。

3 个答案:

答案 0 :(得分:2)

LEFT JOIN即使尚未购买也会允许显示记录。 totalSold的值为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

要进一步了解联接,请访问以下链接:

答案 1 :(得分:2)

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

答案 2 :(得分:1)

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)