简体   繁体   English

如何连接两个表并返回两个表中的所有行

[英]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';中的公共列是'uid';

sql statement for books.书籍的 sql 语句。

SELECT * FROM books ORDER BY TIME DESC;

From the above i get user_id 'uid' and use it in a separate query.从上面我得到 user_id 'uid' 并在单独的查询中使用它。

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 .我想最终得到如下内容,而不是从 table.books 和 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.您必须在数据库中查找 JOIN 的基础,以了解如何连接两个表以检索特定数据。

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) FROM 图书 a INNER JOIN 用户 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.如果你给了 GROUP BY 或任何其他约束,那么在“Where”子句之后使用“and”marge条件。

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这个叫做FULL JOIN,可以在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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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