简体   繁体   English

SQL将两个查询合并为一个

[英]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. 现在,我想从给定作者撰写的书籍中选择一本书,并且购买次数超过X次。

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. 但是我只希望购买的书籍超过X次。

   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. 然后,如果可能的话,我想使用INNER JOIN将其与第一个查询合并。

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. 也许“购买”表应该仅具有BookID作为PK,并具有用于购买次数的字段。

LEFT JOIN will allow records to be shown even if they have not purchase yet. LEFT JOIN将允许显示记录,即使尚未购买也是如此。 The value of totalSold will be 0. 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

To further gain more knowledge about joins, kindly visit the link below: 要进一步获得有关联接的知识,请访问以下链接:

SELECT * FROM
Books INNER JOIN Purchases USING (BookID) 
WHERE AuthorID = ? 
GROUP BY BookID 
HAVING COUNT(BookID) > ?;
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM