在select中计算where子句或子查询计算

时间:2016-01-27 18:27:49

标签: mysql where-clause calculated-columns

我有一个表story,其中包含idtitle。用户可以为每个故事投票或者投票。这是模型:

+-------+      +----------+
| Story |      |   vote   |
+-------+~~~~~~+----------+
| id    |      | id       |
| title |      | story_id |
+-------+      | type     |
               +----------+

typeboolean。 我想获取有关upvote和downvote之间差异的故事>我也想知道这个故事有多少赞成。总而言之,这是我想要得到的结果的一个例子:

+----------+---------+------------+------------+
| story_id | title   | difference | nb_upvotes |
+----------+---------+------------+------------+
| 1        | title 1 | 5          | 45         |
| 4        | title 4 | 32         | 89         |
| 5        | title 5 | 18         | 12         |
+----------+---------+------------+------------+

我试过这个

SELECT s.id,
       s .title,
       Count(v.id) AS upvote
FROM   story s
       INNER JOIN vote mp
               ON v.story_id = s.id
                  AND v.type = 1
WHERE  (SELECT Count(id) up
        FROM   vote
        WHERE  type = 1
               AND story_id = s.id) - (SELECT Count(id) down
                                       FROM   vote
                                       WHERE  type = 0
                                              AND story_id = s.id) > 0
GROUP  BY s.id;  

但我没有得到结果的差异。只有upvotes的数量:

+----------+---------+------------+
| story_id | title   | nb_upvotes |
+----------+---------+------------+
| 1        | title 1 | 45         |
| 4        | title 4 | 89         |
| 5        | title 5 | 12         |
+----------+---------+------------+

我怎么能实现这个目标?

由于

编辑:

感谢@ miken32我得到了这个

SELECT id, title,
    (SELECT COUNT(id) FROM story_moderation WHERE story_id = s.id AND type = 1) AS upvotes,
    (SELECT COUNT(id) FROM story_moderation WHERE story_id = s.id AND type = 0) AS downvotes,
    (SELECT COUNT(id) FROM story_moderation WHERE story_id = s.id AND type = 1) - (SELECT COUNT(id) FROM story_moderation WHERE story_id = s.id AND type = 0) as diff
FROM story s
HAVING upvotes - downvotes > 0

但这是很多子查询,是不是太耗费资源?

1 个答案:

答案 0 :(得分:0)

很难说没有任何东西可以测试,但是这样做了吗?如果要捕获结果集中的任何信息,则必须在SELECT子句中指定。

SELECT id, title,
    (SELECT COUNT(id) FROM vote WHERE story_id = s.id AND type = 1) AS upvotes,
    (SELECT COUNT(id) FROM vote WHERE story_id = s.id AND type = 0) AS downvotes
FROM story s
HAVING upvotes - downvotes NOT IN (-1, 0, 1);