Search code examples
phpmysqljoininner-join

How to Join two tables and return all rows from both tables


I have two tables. Users and Books, I want to join these two tables and return all rows for both tables. The common column in the is 'uid';

sql statement for books.

SELECT * FROM books ORDER BY TIME DESC;

From the above i get user_id 'uid' and use it in a separate query.

And for users.

SELECT * FROM users WHERE uid = '$uid';

I want to end up with something like the following instead of going in and out of the database from table.books and then table.users .

while($row = mysqli_fetch_array($query)){
           echo $row[book_name];
           echo $row[user_firstname];
   }

Thanks.


Solution

  • You have to look for funda of JOINs in database to learn about how to join two tables to retrieve specific data.

    Try this:

    SELECT *
    FROM books b 
    INNER JOIN users u ON b.uid = u.uid 
    ORDER BY b.TIME DESC;