MySQL:选择行直到达到较小的数字

时间:2016-04-13 01:15:27

标签: mysql sql

我正在处理存储过程,在那里我需要显示在任何给定时间检出的大多数书籍。例如,我可以使用表格中的数据生成以下内容:

callNumber          title                NumberCheckedOut
    1             Unbroken                      2
    2             Outliers                      2
    3         Intro to CompSci                  2
    4       One World School House              1
    5          DB For Dummies                   1

对于这个例子,我只想向CompSci显示Unbroken,Outliers和Intro,因为这些书籍是签出最多副本的书籍。

用于生成此存储过程的代码是:

BEGIN

SELECT Book.callNumber, Book.title, Count(Book.callNumber) AS NumCheckedOut
FROM Book, Borrows, Copy
WHERE (Book.callNumber = Borrows.callNumber) AND (Copy.copyNumber = Borrows.copyNumber) AND (Book.callNumber = Copy.callNumber)
GROUP BY Book.callNumber 
ORDER BY Book.callNumber;

END

我可以对此存储过程进行哪些更改,以便只选择签出了最大份数的图书?

1 个答案:

答案 0 :(得分:0)

首先,学会使用正确的显式JOIN语法。简单规则:从不FROM子句中使用逗号。我认为你不需要查询的copy表:

SELECT b.callNumber, b.title, Count(*) AS NumCheckedOut
FROM Book b JOIN
     Borrows bor
     ON b.callNumber = bor.callNumber
GROUP BY b.callNumber 
ORDER BY b.callNumber;

然后,您只需Book即可获取其他信息。

您可以使用HAVING子句进行过滤:

SELECT b.callNumber, b.title, Count(*) AS NumCheckedOut
FROM Book b JOIN
     Borrows bor
     ON b.callNumber = bor.callNumber
GROUP BY b.callNumber 
HAVING COUNT(*) = (SELECT COUNT(*)
                   FROM Borrows
                   GROUP BY callNumber
                   ORDER BY COUNT(*) DESC
                   LIMIT 1
                  )
ORDER BY b.callNumber;