查询结果乘以2

Query results are multiplied by 2

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 个展览(而不是 2 个),并且我在计数组中得到了 4 个结果而不是 2 个。我一直卡在怎么解决这个问题上,可能跟doube left join有关。

最简单的解决方案是在计数上使用 DISTINCT,如果您的 app_results table 上有一个主键,例如 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

或加入已经分组的 table(我假设 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