我正在为我的学校设计一个图书馆申请表。我们有2-3个主要图书馆,有些部门有自己的图书馆。我想知道这些问题是否正确?

Libraries
ID Name
1  Walter
2  Wally
3  Maths dept library

Books
ID Book ID  BookName
1   1       Fundamentals of calculus
2   1       Mechanics
3   2       Fundamentals of calculus
4   2       Biology

Lib_Book_LookUp
ID  libId bookId
1    1     1
2    1     2
3    2     1
4    2     2

我想解决的两个问题是:
发现某本书有多少份
找出哪些图书馆有一本特别的书
以下是我所拥有的:
Select count(Book.bookId) where book.name = "Fundamentals of calculus";

Select count(libId) from Lib_Book_lookUp, Book where Book.BookId = Lib_Book_lookUp.bookId groupBy(libId)

关于这些问题,我的问题是:
是否有必要有一个单独的查找表并将libId合并到Books表中,并将其作为book表上的外键?
这些问题看起来正确吗?

最佳答案

第一个查询缺少FROM子句。您也可以执行COUNT(*),但在这种情况下并不特别重要:

 SELECT count(Book.bookId) FROM Books WHERE BookName = "Fundamentals of calculus";

要找出哪些库有特定的图书,不需要COUNT()聚合。相反,您需要在join中使用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一栏是相当误导人的。有两种不同的书名具有相同的id1
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

关于mysql - 图书馆数据库设计外键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12897013/

10-13 08:47