在MySQL中将两张表合并为一张

时间:2019-09-03 12:41:49

标签: mysql

假设我有两个名为usersoffers的表

users

+----+----------+-----------+
| id | username | role      |
+----+----------+-----------+
| 1  | A        | client    |
+----+----------+-----------+
| 2  | B        | client    |
+----+----------+-----------+
| 3  | C        | candidate |
+----+----------+-----------+
| 4  | D        | candidate |
+----+----------+-----------+
| 5  | E        | candidate |
+----+----------+-----------+

offers

+----+-----------+--------------+
| id | client_id | candidate_id |
+----+-----------+--------------+
| 1  | 1         | 3            |
+----+-----------+--------------+
| 2  | 2         | 4            |
+----+-----------+--------------+
| 3  | 1         | 5            |
+----+-----------+--------------+
| 4  | 2         | 3            |
+----+-----------+--------------+
| 5  | 2         | 5            |
+----+-----------+--------------+

我想创建一个查询来将offers表与users表结合起来,例如

+----+-----------+-----------------+--------------+--------------------+
| id | client_id | client_username | candidate_id | candidate_username |
+----+-----------+-----------------+--------------+--------------------+
| 1  | 1         | A               | 3            | C                  |
+----+-----------+-----------------+--------------+--------------------+
| 2  | 2         | B               | 4            | D                  |
+----+-----------+-----------------+--------------+--------------------+
| 3  | 1         | A               | 5            | E                  |
+----+-----------+-----------------+--------------+--------------------+
| 4  | 2         | B               | 3            | C                  |
+----+-----------+-----------------+--------------+--------------------+
| 5  | 2         | B               | 5            | E                  |
+----+-----------+-----------------+--------------+--------------------+

我编写了2个单独工作的查询,但是我想将它们组合到一个表中。

SELECT offers.candidate_id, users.username AS candidate_username
FROM offers INNER JOIN users ON offers.candidate_id = users.id;

SELECT offers.client_id, users.username AS client_username
FROM offers INNER JOIN users ON offers.client_id = users.id;

2 个答案:

答案 0 :(得分:2)

您可以在下面尝试-

SELECT offers.candidate_id, 
       a.username AS client_username,a1.username as candidate_username 
FROM offers left JOIN users a ON offers.client_id = a.id
left join users a1 ON offers.candidate_id = a1.id

答案 1 :(得分:0)

您可以将Left Join用于此目的,例如:

SELECT offers.candidate_id, 
       a.username AS client_username,a1.username AS candidate_username 
FROM offers left JOIN users a ON offers.client_id = a.id OR offers.candidate_id = a.id;