在SQL中加入GROUP BY和HAVING

时间:2014-04-14 08:09:31

标签: sql join

假设我有这样的架构。 enter image description here

现在我想要查阅至少有五本书结账的借款人的姓名,地址和结账数量。

过了一段时间,我提出了这个解决方案,因为我在数据库中更新鲜:

SELECT BR.Name, BR.Address,
   Checkout.NoOfBookCheckedOut
FROM Borrower BR, (
    SELECT CardNo, COUNT(BookId) AS 'NoOfBookCheckedOut'
    FROM Book_Loans
    WHERE DateOut IS NOT NULL
    GROUP BY CardNo
    HAVING COUNT(BookId) >= 5
 ) AS 'Checkout'
WHERE Checkout.CardNo = BR.CardNo

我的解决方案是否正确?有没有更好的方法来优化此查询?

3 个答案:

答案 0 :(得分:2)

您可以在此处使用内部联接

SELECT BR.Name, BR.Address,
   Checkout.NoOfBookCheckedOut
FROM Borrower BR
INNER JOIN (
    SELECT CardNo, COUNT(BookId) AS 'NoOfBookCheckedOut'
    FROM Book_Loans
    WHERE DateOut IS NOT NULL
    GROUP BY CardNo
    HAVING COUNT(BookId) >= 5
 ) Checkout
ON Checkout.CardNo = BR.CardNo

答案 1 :(得分:1)

我认为您可以通过连接两个表来简化查询,而无需派生表。

SELECT
    BR.Name,
    BR.Address,
    COUNT(BL.BookId) as NoOfBookCheckedOut

FROM
    Borrower BR JOIN Book_Loans BL ON BR.CardNo = BL.CardNo

WHERE
    BL.DateOut IS NOT NULL

GROUP BY
    BR.Name,
    BR.Address

HAVING
    COUNT(BL.BookId) >= 5

答案 2 :(得分:0)

要优化查询,请确保在join和where子句中使用的列上有适当的索引。