简体   繁体   中英

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.

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;

SELECT a. ,b. FROM books a INNER JOIN users b ON (a.id = b.uid)

Try with below query for the all data from both tables without any filtration

select * from Users u,Books b where u.user_id=b.uid

if you given GROUP BY or any other Constrains then after the "Where" clause using the "and" marge the conditions.

This return all rows from books and users

SELECT * 
FROM books b 
FULL OUTER JOIN users u ON b.uid=u.uid;

从books 中选择books.bookname,users.user_firstname 加入books.id=users.id 上的用户

Try this it will work :

Use Inner Join

SELECT t1.*,t2.`user_firstname` FROM books t1
    JOIN users t2 ON t2.`uid` = t1.`uid`

This is called FULL JOIN, you can implement it in MySql

SELECT *
FROM books AS b 
LEFT JOIN users AS u ON b.uid = u.uid 

UNION

SELECT *
FROM books AS b 
RIGHT JOIN users AS u ON b.uid = u.uid

With order

SELECT t.*
FROM (
    SELECT *
    FROM books AS b 
    LEFT JOIN users u ON b.uid = u.uid 

    UNION

    SELECT *
    FROM books AS b 
    RIGHT JOIN users AS u ON b.uid = u.uid 
) t
ORDER BY t.TIME DESC;
SELECT b.*, u.uid
FROM books b 
INNER JOIN users u ON b.uid = u.uid 
ORDER BY b.TIME DESC;

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