I'm new to SQL and can't figure this simple thing out. I have two tables:
+----------+----------+
| Person_1 | Person_2 |
+----------+----------+
| 1 | 2 |
| 1 | 4 |
| 3 | 2 |
+----------+----------+
and
+----+------+
| ID | City |
+----+------+
| 1 | A |
| 2 | B |
| 3 | A |
| 4 | A |
+----+------+
The values in columns Person_A and Person_B refer to the ID in the second table. I want to combine these two tables to have a resulting table like this:
+----------+----------+---------------+---------------+
| Person_1 | Person_2 | Person_1_City | Person_2_City |
+----------+----------+---------------+---------------+
| 1 | 2 | A | B |
| 1 | 4 | A | A |
| 3 | 2 | A | B |
+----------+----------+---------------+---------------+
How can I do this?
Use JOIN
with city twice:
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
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.