2
article_vote table
+------------+------+
| article_id | vote |
+------------+------+
|          1 |    3 |
|          1 |    1 |
|          1 |   -1 |
|          1 |   -2 |
+------------+------+

在 MySQL 5.5 中,我一直试图从上表中返回两个结果。1. 所有反对票的总和。2. 所有正票的总和。所以正数应该是4负数应该是-3。投票字段没有 NULL 值。

此 SQL 不能按我的意图工作:

SELECT vote,
    SUM(vote > 0) AS positive,
    SUM(vote < 1) AS negative
FROM article_vote
WHERE vote_article_id = 50
GROUP BY vote

当我在上面的数据集上使用它时,它返回:

Array ( [vote] => -22 [positive] => 0 [negative] => 1 ) 

我哪里错了?

4

4 回答 4

3

试试这个:

SELECT
    SUM(if(vote > 0, vote, 0)) positive,
    SUM(if(vote < 0, vote, 0)) negative
FROM article_vote
WHERE article_id = 1

结果:

| POSITIVE | NEGATIVE |
|----------|----------|
|        4 |       -3 |

在这里拉小提琴。

于 2013-10-27T04:33:40.347 回答
2
mysql> SELECT * FROM article_vote;
+------------+------+
| article_id | vote |
+------------+------+
|          1 |    3 |
|          1 |    1 |
|          1 |   -1 |
|          1 |   -2 |
+------------+------+
4 rows in set (0.00 sec)

SELECT 
    SUM(CASE WHEN vote > 0 THEN vote ELSE 0 END) AS positive,
    SUM(CASE WHEN vote < 0 THEN vote ELSE 0 END) AS negative
FROM article_vote
WHERE article_id = 1;

+----------+----------+
| positive | negative |
+----------+----------+
|        4 |       -3 |
+----------+----------+

http://sqlfiddle.com/#!2/c18e3/1

于 2013-10-27T04:32:44.700 回答
2

纠正这样的事情:

select article_id, 
  sum(case when vote >0 then vote else 0 end) as postive,
  sum(case when vote <0 then vote else 0 end) as negative
FROM article_vote
GROUP BY article_id

不确定您的位置条件,对不起。

于 2013-10-27T04:34:31.320 回答
1

你可以尝试这样的事情:

SELECT article_id,

    (SELECT SUM(vote) 
     FROM article_vote 
     WHERE vote > 0 
     AND article_id = 50) AS positive,

    (SELECT SUM(vote)
     FROM article_vote
     WHERE vote < 0
     AND article_id = 50) AS negative

FROM article_vote
WHERE article_id = 50
GROUP BY article_id
于 2013-10-27T04:25:11.130 回答