Reputation: 191
I have a users table, books table and authors table. An author can have many books, while a user can also have many books. (This is how my DB is currently setup). As I'm pretty new to So far my setup is like bookview.php?book_id=23
from accessing authors page, then seeing all books for the author. The single book's details are all displayed on this new page...I can get the output to display the user ID associated with the book, but not the user name, and this also applies for the author's name, I can the author ID to display, but not the name, so somewhere in the query below I am not calling in the correct values:
SELECT users.user_id,
authors.author_id,
books.book_id,
books.bookname,
books.bookprice,
books.bookplot
FROM books
INNER JOIN authors on books.book_id = authors.book_id
INNER JOIN users ON books.book_id = users.user_id
WHERE books.book_id=" . $book_id;
Could someone help me correct this so I can display the author name and user name both associated with the book! Thanks for the help :)
Upvotes: 1
Views: 595
Reputation: 428
I think the right join conditions would be something like (changes bolded)
SELECT users.user_id,
**users.user_name,**
authors.author_id,
**authors.author_name,**
books.book_id,
books.bookname,
books.bookprice,
books.bookplot
FROM books
INNER JOIN authors on books.**author_id** = authors.**author_id**
INNER JOIN users ON books.**user_id** = users.user_id
WHERE books.book_id=" . $book_id;
Or you can use the less verbose syntax for simple inner joins.
SELECT users.user_id,
users.user_name,
authors.author_id,
authors.author_name,
books.book_id,
books.bookname,
books.bookprice,
books.bookplot
FROM books, authors, users
where books.author_id = authors.author_id
and books.user_id = users.user_id
and books.book_id=" . $book_id
Upvotes: 1
Reputation: 881705
These two joins together:
INNER JOIN authors on books.book_id = authors.book_id
INNER JOIN users ON books.book_id = users.user_id
also imply authors.book_id = users.user_id
which, on the face of it, makes no sense. Surely the code you've posted is not the code you're actually using...?
Upvotes: 0