将查询spoecific结果合并在一行中

时间:2015-05-11 11:14:23

标签: php mysql

我得到了一个关于MySQL的问题并找到了正确的查询。

目前我收到了这个问题:

SELECT f.id
 , f.name 
 , e.name as exhibition_name
 , l.name as `language`
FROM `app_forms` f
LEFT JOIN  `app_exhibitions` e ON(f.id = e.form_id )
LEFT JOIN `app_forms_translations` ft ON(ft.form_id = f.id )
LEFT JOIN `app_languages` l ON(ft.lang_id = l.id)

这结合了以下表格中的记录:

app_exhibitions
-id
-name
-location
-form_id

app_forms
-id
-name

app_form_translations
-id
-form_id
-lang_id
-content

app_languages
-id
-name
-code

但是现在如果单个展览有多个表格,我会得到多个记录,这些表格形成双重但每个展览都有不同的展览。我希望他们分组,这样我每张表格都会有一行,但展览会与concat组合在一起。

我已经尝试了这个,但是我在展览栏中列出了每个展览名称的一条记录。

SELECT f.id
     , f.name 
     , group_concat(e.name separator ',') as exhibition name
     , l.name as `language`
FROM `app_forms` f
LEFT JOIN  `app_exhibitions` e ON(f.id = e.form_id )
LEFT JOIN `app_forms_translations` ft ON(ft.form_id = f.id )
LEFT JOIN `app_languages` l ON(ft.lang_id = l.id)

1 个答案:

答案 0 :(得分:1)

您需要group by

SELECT f.id,
       f.name,
       group_concat(e.name separator ',') as exhibition name,
       l.name as `language`
FROM `app_forms` f
LEFT JOIN  `app_exhibitions` e ON(f.id = e.form_id )
LEFT JOIN `app_forms_translations` ft ON(ft.form_id = f.id )
LEFT JOIN `app_languages` l ON(ft.lang_id = l.id)
GROUP BY f.id, f.name, l.name;