Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore duplicate rows in COUNT

Tags:

sql

mysql

The following query gives a count of how many rows there are in the exp_judging table with a value of 1 in the field pre, where there is also a matching column in exp_submissions with a member_group of 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

This works great. However, in the future there will be multiple rows with the same 'rel_id' in the 'exp_judging' table.

How can I ensure that only one of each row is counted?

I tried adding GROUP BY to the end, but it just shows 1 result then, instead of 4 before. (there are no duplicates yet)

GROUP BY jud.rel_id

EDIT:

Have tried the following, but still just shows 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
like image 273
ccdavies Avatar asked Oct 03 '13 07:10

ccdavies


1 Answers

Use COUNT(DISTINCT rel_id) instead of COUNT(*).

like image 158
Mahmoud Gamal Avatar answered Oct 16 '22 18:10

Mahmoud Gamal