2016-11-21 38 views
-9

我有2表[表1,表2]加入表中多列

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 | 
+------------+------------+----------+ 

我怎樣才能做到這一點?

+2

普拉德,你嘗試過這麼遠嗎?爲什麼它不工作?如果您提供更多信息,人們會更容易幫助您。請查看幫助中心的[問]文章。 – Gulllie

+3

你正在使用哪個dbms。 (刪除兩個標記的。) – jarlh

回答

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 
+1

如果你想獲得三列的名稱,比是:) – Wouter

+0

感謝它爲我工作, –