I’m pulling a grouping of comment types and their totals from a mySQL database. The result set looks like:
ID – NAME – TOTAL
0 – GENERAL – 4
3 – MEANINGFUL – 9
4 – MISC – 5
In my output to the end user, however, I want to sum the totals for GENERAL and MISC, IDs 0 and 4. How should I efficiently do this? The problem I’m seeing is that ID 0 might not be in every result and the same thing for ID 4.
Any suggestions?
My query is:
SELECT a.fk_type_id as ID, count(a.fk_type_id) as TOTAL, b.vch_name as NAME
FROM comments a
LEFT JOIN comments_types b ON a.fk_type_id = b.id
WHERE a.entry = X
GROUP BY a.fk_type_id
So my end-user result should look like:
GENERAL/MISC – 9
MEANINGFUL – 9
I would make it easy on you and MySQL and split it out like this:
I changed your
LEFT JOINtoJOINbecause we’re only counting comments with a type.You might improve this query, assuming an index on
fk_type_id, by making ‘MISC’ type ‘1’ instead of type ‘4’, so you could do something likea.fk_type_id < 2instead of (a.fk_type_id = 0 OR a.fk_type_id = 4) anda.fk_type_id > 1instead ofa.fk_type_id <> 0 AND a.fk_type_id <> 4.If you’re utilizing indexes instead of scanning rows, performing two separate queries that return different results won’t affect performance.