I’m designing a library application for my school. We have a 2-3 main libraries and some departments have their own libraries. I wanted to know whether these queries seem correct ?
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
The two questions I want to solve are:
- Find how many copies of a particular book exist
- Find out which libraries have a particular book
Here’s what I have:
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)
My questions regarding these queries:
- Does it seem unnecessary to have a separate lookup table and merge the libId into Books table and have it as a foreign key on the book table ?
- Do the queries seem correct ?
Your first query is missing a
FROMclause. You could also doCOUNT(*), but it doesn’t particularly matter in this case:To find out which libraries have a particular book, you don’t need a
COUNT()aggregate. Instead you need aWHEREclause with your join. TheCOUNT()would tell you how many libraries have a book, but not which libraries. For that you want a query which returnsLibraries.Name.The lookup table is appropriate because it allows you to normalize books down to a single record in the
Bookstable if it exists in multiple libraries. As you have it, there is no real reason to have multiple copies in theBookstable, and no reason for theBook IDcolumn. In fact, theBook IDcolumn as it is is quite misleading. There are books with two different titles having the same id1.The
Bookstable really ought to look like the following, with one record per book title (assuming title as the authority, forgetting about real authoritative things like ISBN)If you have multiple copies of each book possible at each library, you may consider normalizing the books per copy into a table that identifies them by library barcode. You would then match those ids to libraries as holdings:
To query, for example, the number of copies per book per library, you would use: