MySQL查询。从三个表中选择数据

时间:2010-12-15 08:33:25

标签: sql mysql

我有三张桌子:

语言 (id,lang_name,已发布)

翻译 (身份证,姓名,姓名,电话,电子邮件,已发布)

trans_lang_rel (语言和翻译关系。一位译员可以翻译一种或多种语言)

id,trans_id,lang_id

表格中的数据:

语言

1英语1
2俄罗斯1
3德语1

翻译

1 Name1 Surname1 999 name1.surname1@gmail.com 1
2 Name2 Surname2 888 name2.surname2@gmail.com 1

trans_lang_rel

1 1 1
2 1 2
3 2 1

所以我必须从这三个表中选择数据。

结果应该是这样的:

Name1 |姓氏1 |英语,俄语| 999 | name1.surname1@gmail.com

我尝试过这样的事情,但结果很奇怪:

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 

我们将不胜感激。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 

答案 2 :(得分: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