MySQL计数自

时间:2012-07-09 12:38:53

标签: mysql sql

我想知道如何使用mysql查询解决以下问题,但不知道如何继续

我有3张桌子(我会尽量保持简单)

          post

       id  | content 
           |
       1   | bla, bla..

          comment                          |                votes
                                           |
id | post_id | comment | date              |        id | comment_id | date 
                                           |           |            |
5  |    1    |  derp   | 2012-07-06        |        1  |     5      | 2012-07-07
6  |    1    |  nherp  | 2012-07-07        |        2  |     5      | 2012-07-08
7  |    1    |  yada   | 2012-07-08        |        3  |     5      | 2012-07-09
8  |    1    |  lala   | 2012-07-09        |        4  |     6      | 2012-07-10
                                           |        5  |     6      | 2012-07-11    
                                           |        6  |     7      | 2012-07-12
                                           |        7  |     8      | 2012-07-13
                                           |

他们以这种方式相互联系

comment.post_id是post.id的fk

votes.comment_id是评论的fk.id

我想要发现的是,每次评论后,整个帖子的票数是多少。或者换句话说,在提交每条评论后,已经对整个帖子投了多少票。 因此,对于我提出的这个案例,我期待的结果将是下表

                                      result

                  id | post_id | comment | date        | votes_after_submission
                     |         |         |             | 
                  5  |    1    |  derp   | 2012-07-06  |          7
                  6  |    1    |  nherp  | 2012-07-07  |          6
                  7  |    1    |  yada   | 2012-07-08  |          5
                  8  |    1    |  lala   | 2012-07-09  |          4

这给了我的大脑一个结,我尝试在COUNT语句中使用CASE关键字,但实际上无法让它适用于这个问题,任何人都可以给我一些线索,或指向我正确的方向或者也许只是给我一些谷歌关键词搜索,因为我没有找到任何关于这个问题。

3 个答案:

答案 0 :(得分:0)

试试这个::

select 
comment.id,
post_id, comment,
date,
count(votes.id) as no_of_vote
from comment
inner join votes on (comment.id=votes.comment_id)
group by comment.id

答案 1 :(得分:0)

试试这个:

select comment.id, comment.post_id, comment.date, count(1) Votes
    from comments, votes
    where comments.id = votes.comment_id and votes.date >= comments.date
    group by comment.id, comment.post_id, comment.date, 

答案 2 :(得分:0)

如果我理解您的问题和示例结果,请尝试以下方法:

SELECT C.id,C.post_id,C.comment,C.date, 
       (SELECT COUNT(*)
        FROM votes AS V 
        WHERE V.date > C.date 
          AND V.comment_id IN (SELECT id FROM comment AS C2 
                               WHERE C2.post_id=C.post_id)) AS votes_after_submission
FROM comment AS C
ORDER BY C.post_id, C.date

我不确定它是最有效的,但它确实有效。