I have two tables:
comments (
id int
comment int
)
commentvotes (
commentid int
positive bool
)
Where commentvotes.positive determines whether a vote was an upvote or a downvote.
Is there any way, with a single query, that I can get all of the upvotes and downvotes, ideally in a column each? More generally, can you run two counts with different selection criteia in the same query?
You can do stupid tricks with
SUM:MySQL booleans are actually just integers, 0 or 1. Adding them up effectively counts how many times a condition is true. So if you have:
Then
SUM(positive)is1+1+0+1+0= 3.SUM(NOT positive)is0+0+1+0+1= 2. You can do this in other databases, too, but usually need an explicit cast.One caveat: because MySQL has no real boolean type, your
positivecolumn is actuallyTINYINT(1), and could contain any number that fits in a byte, which will throw offSUM(positive). You can useSUM(NOT NOT positive), or a cast, or use a database that doesn’t lie to you quite so much. 😉If this is all too arcane for you (rightfully so), the easy way out is to denormalize a bit and give
commentsupvotesanddownvotescolumns. Or you could use a subquery for upvotes and another for downvotes, but in my experience MySQL is particularly bad with grouping operations and subqueries.