我正在处理存储过程,在那里我需要显示在任何给定时间检出的大多数书籍。例如,我可以使用表格中的数据生成以下内容:
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
我可以对此存储过程进行哪些更改,以便只选择签出了最大份数的图书?
答案 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;