查询结果乘以2

时间:2015-06-09 10:11:07

标签: mysql left-join

3张桌子。 app_forms, app_results, app_exhibitions

我想获取表单ID,表单名称,结果计数以及与表单相关的展览。目前我得到了这个问题:

SELECT 
f.id as id, 
f.name as formname, 
count(res.form_id) as resultcount, 
group_concat(b.name separator ', ') as exhibitionname 
FROM app_forms f 
LEFT JOIN app_results res ON f.id = res.form_id 
LEFT JOIN app_exhibitions exh ON exh.form_id = f.id 
GROUP by f.id

问题是,它将事物乘以2.因为我在concat组中有4个exhbition(而不是2个),我在计数组中得到4个结果而不是2个结果。我陷入了如何解决这个问题,它可能与doube left join有关。

1 个答案:

答案 0 :(得分:3)

最简单的解决方案是在计数上使用DISTINCT,如果app_results表上有主键,例如app_results.id:

SELECT 
  f.id as id, 
  f.name as formname, 
  count(DISTINCT res.id) as resultcount, 
  group_concat(b.name separator ', ') as exhibitionname 
FROM
  app_forms f LEFT JOIN app_results res ON f.id = res.form_id 
  LEFT JOIN app_exhibitions exh ON exh.form_id = f.id 
GROUP by f.id

或加入已经分组的表(我认为b.name是exh.name):

SELECT 
  f.id as id, 
  f.name as formname, 
  count(res.form_id) as resultcount, 
  exh.exhibitionname 
FROM
  app_forms f LEFT JOIN app_results res ON f.id = res.form_id 
  LEFT JOIN (
    SELECT form_id, group_concat(name separator ', ') as exhibitionname
    FROM app_exhibitions
    GROUP BY form_id
  ) exh ON exh.form_id = f.id 
GROUP by f.id