假设我有两个名为users
和offers
的表
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;
答案 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;