SQL列值基于另一个表中的值

时间:2019-03-13 19:06:08

标签: sql

我是SQL的新手,无法弄清楚这个简单的事情。 我有两个桌子:

+----------+----------+
| Person_1 | Person_2 |
+----------+----------+
|        1 |        2 |
|        1 |        4 |
|        3 |        2 |
+----------+----------+

+----+------+
| ID | City |
+----+------+
|  1 | A    |
|  2 | B    |
|  3 | A    |
|  4 | A    |
+----+------+

Person_A和Person_B列中的值引用第二个表中的ID。我想将这两个表合并成这样的结果表:

+----------+----------+---------------+---------------+
| Person_1 | Person_2 | Person_1_City | Person_2_City |
+----------+----------+---------------+---------------+
|        1 |        2 | A             | B             |
|        1 |        4 | A             | A             |
|        3 |        2 | A             | B             |
+----------+----------+---------------+---------------+

我该怎么做?

1 个答案:

答案 0 :(得分:2)

对城市使用两次JOIN

select p.persion1, p.persion2, 
  c1.city as persion1city,
  c2.city as persion2city
from  person p
left join city c1 on p.Person_1 = c1.id
left join city c2 on p.Person_2 = c2.id