简体   繁体   中英

How to Query across multiple tables

I have the following DB. Is this a proper query to get the first name of the authors loaned by Members ? or is there a more efficient way ?

select M.MemberNo, A.FirstName
from Person.Members as M
INNER JOIN Booking.Loans as L
on M.MemberNo = L.MemberNo
INNER JOIN Article.Copies as C
on L.ISBN = C.ISBN and L.CopyNo = C.CopyNo
INNER JOIN Article.Items as I
on C.ISBN = I.ISBN
INNER JOIN Article.Titles as T
on I.TitleID = T.TitleID
INNER JOIN Article.TitleAuthors as TA
on T.TitleID = TA.TitleID
INNER JOIN Article.Authors as A
on TA.AuthorID = A.AuthorID
;
go

在此处输入图片说明

The most direct way to get the names of authors of books that are lent out to members would be like this:

  1. Get member loans (Booking.Loans)
  2. Get books for member loans (Article.Items)
  3. Get authors for the books for member loans (Article.TitleAuthors)
  4. Get first names for authors for the books for member loans (Article.Authors)
 select L.MemberNo, A.FirstName FROM Booking.Loans as L INNER JOIN Article.Items as I on L.ISBN = I.ISBN INNER JOIN Article.TitleAuthors as TA on I.TitleID = TA.TitleID INNER JOIN Article.Authors as A on TA.AuthorID = A.AuthorID 

The advantage to joining all the tables like you have your original query is to ensure that each intermediary table was INSERTed into or DELETEd from correctly.

For example, your original query wouldn't return any rows for a member if they had a loan (ie a row in the Loans table) but for some reason didn't have an entry in the Members table. If you can assume that (or don't care if) there will always be a row in the Members table if there is a row in the Loans table, then you can exclude the join to Person.Members.

You can apply this same logic to the other intermediary tables (Member, Copies, Title) too, if needed. If you need a specific piece of data from one of the these tables, though, then you would need to include them in the joins.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM