简体   繁体   中英

SQL Query for related Table with pair of id´s from another table (show names instead id´s)

I have two related Tables. The first table (tbl1) is like

ID | name

  • 1 | X
  • 2 | Y
  • . |.
  • . |.
  • . |.

And the second table (tbl2)

ID1 | ID2

  • 2 | 1
  • . |.
  • . |.
  • . |.

So, I try to write a SQL Query to show me the names like this:

Name1 | Name2

  • Y | X
  • . |.
  • . |.
  • . |.

I tried this SQL:

SELECT tbl1.name, tbl1.name FROM tbl2
INNER JOIN tbl1 ON tbl2.id_tbl1 = tbl1.id
INNER JOIN tbl1 AS t1 ON tbl2.id_tbl1 = t1.id;

But it doesn´t work. Can someone show me a SQL Query for my problem please?

Two joins are the right way to go. But you need to refer to the aliases:

SELECT t1_1.name, t1_2.name
FROM tbl2 t2 JOIN
     tbl1 t1_1
     ON t2.id_tbl1 = t1_1.id JOIN
     tbl1 t1_2 
     ON t2.id_tbl1 = t1_2.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.

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