2010-12-15 198 views
0

選擇數據我有三個表:MySQL查詢。從三個表

語言 (ID,LANG_NAME,出版)

翻譯 (ID,姓名,電話,電子郵件,出版)

trans_lang_rel(語言和翻譯者關係,一個翻譯者可以翻譯一種或多種語言)

ID,TRANS_ID,在表LANG_ID

數據:

語言

1英語1
2俄羅斯1
3德國1

翻譯

1名1 Surname1 999 [email protected] 1
2名稱2 Surname2 888 [email protected] 1

trans_lang_rel

所以我必須從這三個表中選擇數據。

結果應該是這樣的:

名稱1 |姓氏1 |英文,俄文| 999 | [email protected]

我已經試過這樣的事情,但是我得到了奇怪的結果:

SELECT t.*, 
GROUP_CONCAT(l.lang_name SEPARATOR ", ") AS language 
FROM translators AS t, 
trans_lang_rel AS tlr 
LEFT JOIN language AS l ON l.id = tlr.lang_id ORDER BY t.id 

您的幫助,將不勝感激。

回答

1

試着這麼做

SELECT t.name, 
     t.surname, 
     GROUP_CONCAT(l.lang_name SEPARATOR ", "), 
     t.phone, 
     t.email 
FROM translators t INNER JOIN 
     trans_lang_rel tlr ON t.id = tlr. trans_id INNER JOIN 
     language l ON tlr.lang_id = l.id 
GROUP BY t.name, 
      t.surname, 
      t.phone, 
      t.email 
0

你加入翻譯的方式和trna_lang_rel不好。你犯了一個full join,因爲你永遠不但是任何ON條款

SELECT t.*, 
GROUP_CONCAT(l.lang_name SEPARATOR ", ") AS language 
FROM translators t 
JOIN trans_lang_rel tlr ON t.id = trans_id 
LEFT JOIN language AS l ON l.id = tlr.lang_id 
ORDER BY t.id 
0
SELECT 
    translators.name, 
    translators.surname, 
    GROUP_CONCAT(language.name SEPARATOR ", ") AS language, 
    translators.phone, 
    translators.email 
FROM 
    translators 
LEFT OUTER JOIN 
    trans_lang_rel 
ON 
    trans_lang_rel.trans_id = translators.id 
LEFT OUTER JOIN 
    language 
ON 
    trans_lang_rel.lang_id = language.id