您的第一个查询缺少一个FROM
子句。您也可以这样做COUNT(*)
,但在这种情况下并不特别重要:
SELECT count(Book.bookId) FROM Books WHERE BookName = "Fundamentals of calculus";
要找出哪些图书馆有一本特定的书,您不需要COUNT()
汇总。相反,您需要一个WHERE
带有连接的子句。会COUNT()
告诉你有多少图书馆有一本书,而不是哪些图书馆。为此,您需要一个返回的查询Libraries.Name
。
SELECT
/* Return library names */
Libraries.Name
FROM
Libraries
/* Join through your lookup table to match a book name to a library name */
JOIN Lib_Book_LookUp ON Libraries.ID = Lib_Book_LookUp.libId
JOIN Books ON Books.ID = Lib_Book_LookUp.bookId
/* Which book to search for */
WHERE Books.BookName = 'Fundamentals of calculus'
Books
查找表是合适的,因为如果它存在于多个图书馆中,它允许您将书籍规范化为表中的单个记录。正如你所拥有的,没有真正的理由在Books
表中有多个副本,也没有理由在Book ID
列中。实际上,该Book ID
列本身具有很大的误导性。有两个不同标题的书具有相同的 id 1
。
该Books
表实际上应该如下所示,每个书名有一条记录(假设标题为权威,忘记像 ISBN 之类的真正权威的东西)
Books
ID BookName
1 Fundamentals of calculus
2 Mechanics
3 Biology
如果您在每个图书馆可能有每本书的多个副本,您可以考虑将每个副本的书籍标准化为一个通过图书馆条形码标识它们的表格。然后,您将这些 id 与图书馆相匹配作为馆藏:
Books (defines bibliographic details)
ID BookName
1 Fundamentals of calculus
2 Mechanics
3 Biology
Book_Copies (Matches Books.ID to barcode, barcode is Primary Key)
BookId Barcode
1 1234567
1 1234568
2 8654321
2 8654322
Lib_Book_LookUp (matches book copies to libraries, allowing multiple copies by barcode)
ID libId bookBarcode
1 1 1234567
2 1 1234568
3 2 8654321
4 2 8654322
例如,要查询每个图书馆每本书的副本数,您可以使用:
SELECT
Libraries.Name,
Books.BookName,
COUNT(*)
FROM
Libraries
JOIN Lib_Book_LookUp ON Libraries.ID = Lib_Book_LookUp.libId
JOIN Book_Copies ON Lib_Book_Lookup.bookBarcode = Book_Copies.Barcode
JOIN Books ON Book_Copies.BookId = Books.ID
GROUP BY
Libraries.Name,
Books.BookName