开发者

Count() arithmetic in mysql

I have two tables:

comments (
  id        int
  comment   int
)

commentvotes (
  commentid int
  positive  bool
)

Where commentvotes.positive determines whether a vote was an upvo开发者_JAVA技巧te 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:

SELECT commentid, SUM(positive) upvotes, SUM(NOT positive) downvotes FROM commentvotes;

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:

commentid | positive
----------|---------
 1        |  true
 1        |  true
 1        |  false
 1        |  true
 1        |  false

Then SUM(positive) is 1+1+0+1+0 = 3. SUM(NOT positive) is 0+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 positive column is actually TINYINT(1), and could contain any number that fits in a byte, which will throw off SUM(positive). You can use SUM(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 comments upvotes and downvotes columns. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜