简体   繁体   中英

Query Link Table SQL

I am having trouble wrapping my head around a simple query. I have a Link table like this:

+----------+----------+
| SourceID | TargetID |
+----------+----------+
| 1        | 2        |
+----------+----------+
| 1        | 3        |
+----------+----------+
| 3        | 4        |
+----------+----------+
| 3        | 5        |
+----------+----------+

And a table of Names

+----------+----------+
| ID       | Name     |
+----------+----------+
| 1        | Mitch    |
+----------+----------+
| 2        | Cheryl   |
+----------+----------+
| 3        | Sue      |
+----------+----------+
| 4        | Harry    |
+----------+----------+
| 5        | Bob      |
+----------+----------+

And I desire output like so. Structured just like the link table, but with the names instead.

+------------+------------+
| SourceName | TargetName |
+------------+------------+
| Mitch      | Cheryl     |
+------------+------------+
| Mitch      | Sue        |
+------------+------------+
| Sue        | Harry      |
+------------+------------+
| Sue        | Bob        |
+------------+------------+

Thanks for the help.

You have to join the names table twice with different aliases. Change the join to left join if the link table will have id's that are not in names .

Fiddle

select t1.name as sourcename, t3.name as targetname
from link t2
join names t1 on t1.id = t2.sourceid
join names t3 on t3.id = t2.targetid

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.

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