我有2个表[table1,table2]
Table 1
+----+------------+
| id | name |
+--+--------------+
| 2 | Film |
| 1 | Music |
| 3 | OTHER |
| 5 | Sports |
| 4 | TV Content |
+----+------------+
Table 2
+----+-----+-----+
| id | id1 | id2 |
+----+-----+-----+
| 2 | 1 | 1 |
| 1 | 1 | 1 |
| 3 | 2 | 1 |
| 5 | 3 | 1 |
| 4 | 4 | 1 |
+----+-----+-----+
我想要的输出是
+------------+------------+----------+
| id_name | id1_name | id2_name |
+------------+------------+----------+
| film | Music | Music |
| music | Music | Music | Required Output
| other | Film | Music |
| sports | OTHER | Music |
| TV Content | TV Content | Music |
+------------+------------+----------+
我该怎么做?
答案 0 :(得分:1)
由于您有三个不同的外键,您需要使用同一个表执行3个不同的连接:
SELECT table1.name AS 'id_name',
first.name AS 'id1_name',
second.name AS 'id2_name'
FROM table2
JOIN table1 ON
table1.id = table2.id
JOIN table1 first ON
first.id = table2.id1
JOIN table1 second ON
second.id = table2.id2