0

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

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。

我愿意接受设计有缺陷。也许购买表应该简单地将 BookID 作为 PK 并有一个购买数量的字段。

4

3 回答 3

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

要进一步了解有关联接的更多信息,请访问以下链接:

于 2013-02-09T16:01:51.763 回答
2
SELECT * FROM
Books INNER JOIN Purchases USING (BookID) 
WHERE AuthorID = ? 
GROUP BY BookID 
HAVING COUNT(BookID) > ?;
于 2013-02-09T16:04:05.607 回答
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)
于 2013-02-09T16:06:15.670 回答