忽略COUNT中的重复行

时间:2013-10-03 07:11:07

标签: mysql sql

以下查询给出exp_judging表中有多少行的计数,字段pre中的值为1,其中exp_submissions中的匹配列的成员组为5

SELECT COUNT(*) AS count_result
  FROM exp_judging AS jud
  LEFT JOIN exp_submissions AS sub ON jud.rel_id = sub.id 
  WHERE jud.pre = 1
        AND sub.member_group = 5

这很有效。但是,将来在'exp_judging'表中会有多行具有相同的'rel_id'。

如何确保每行只计算一行?

我尝试将GROUP BY添加到最后,但它只显示1个结果,而不是之前的4个结果。 (还没有重复)

GROUP BY jud.rel_id

编辑:

尝试过以下内容,但仍然只显示1:

SELECT COUNT(DISTINCT jud.rel_id) AS count_result
FROM exp_judging AS jud
LEFT JOIN exp_submissions AS sub ON jud.rel_id = sub.id 
WHERE jud.pre = 1
AND sub.member_group = $member_group
GROUP BY jud.rel_id

2 个答案:

答案 0 :(得分:16)

使用COUNT(DISTINCT rel_id)代替COUNT(*)

答案 1 :(得分:0)

尝试以下查询

 SELECT COUNT(jud.rel_id) AS count_result
 FROM exp_judging AS jud
 LEFT JOIN exp_submissions AS sub ON jud.rel_id = sub.id 
 WHERE jud.pre = 1
    AND sub.member_group = 5
group by jud.rel_id