views:

130

answers:

1

I am writing an application that helps book exchange between users. I am using PHP and MySQL, and I am pretty new to them both.

I have 5 tables, 3 data tables and 2 service tables:

  1. user: with user attributes (user_id, name, birth... etc).

  2. book: with book attributes (book_id, name, author, publisher... etc).

  3. copy: represents actual copies of a books (copy_id, condition, comments... etc).

  4. user_copy: describes which user holds which copy, composed out of userID and copyID.

  5. copy_book: represents the connection of copy and book, composed out of copyID and bookID

My question is: what is the easiest and most efficient statement for getting the book attributes and copy attributes for each copy that a user holds?

+3  A: 

You need to inner join all the tables that you are interested in: book, copy, user_copy, and copy_book. The SELECT statement that returns attributes on all copies held by a user may look like this:

SELECT   B.bookID
       , B.name
       , B.author
       , B.publisher
       , C.condition
       , C.comments
       -- you may get other fields that you are interested in here..
  FROM book B
       INNER JOIN copy_book CB ON B.bookID = CB.bookID
       INNER JOIN user_copy UC ON UC.copyID = CB.copyID
       INNER JOIN copy C ON C.copyID = UC.copyID
  WHERE UC.userID = <the user Id that you want>

I hope it's pretty clear what the statement does but if you have any questions, please ask.

Miky Dinescu