【问题标题】:Stackoverflow-like comments voting SQL query类似 Stackoverflow 的评论投票 SQL 查询
【发布时间】:2012-11-15 14:02:20
【问题描述】:

我正在开发一个评论系统,例如 Stackoverflow 或 Disqus,人们可以在其中对 cme​​ts 进行评论和投票。我为此准备了三个表:USERSCOMMENTSVOTES

我无法弄清楚如何编写查询来计算投票并返回给定用户是否投票。每个用户每条评论只能投票一次,不能对自己的评论投票。此外,cmets 和投票不只是针对一个主题。每个页面都有自己的主题,因此在对 SELECT 进行 GET 和投票时,WHERE topic_id='X' 也需要反映在查询中。

这是我的表的数据,到目前为止我的查询看起来如何,以及我希望它返回什么:

USERS table
user_id user_name   
 1         tim
 2         sue
 3         bill 
 4         karen
 5         ed

COMMENTS table
comment_id topic_id    comment   commenter_id
 1            1       good job!         1
 2            2       nice work         2
 3            1       bad job :)        3

VOTES table
 vote_id    vote  comment_id  voter_id
  1          -1       1          5
  2           1       1          4
  3           1       3          1
  4          -1       2          5
  5           1       2          4

SELECT users.*, comments.*, count(vote as totals), sum(vote=1 as yes), sum(vote=-1 as no),
my_votes.vote as did_i_vote, users.* as IM_THE_USER
from comments
join votes 
on comments.comment_id=votes.comment_id
join users
on comments.commenter_id=users.user_id
join votes as MY_votes
on MY_votes.voter_id=IM_THE_USER.user_id
where topic_id=1 and IM_THE_USER.user_id=1
group by comment_id

user_id user_name comment_id topic_id  comment   commenter_id  totals yes no did_i_vote
   1      tim          1        1      good job!     1           2     1   1    NULL  
   3      bill         3        1      bad job:)     3           1     1   0      1

【问题讨论】:

    标签: mysql sql voting comments


    【解决方案1】:

    SQL Fiddle

    select u.user_id, u.user_name,
           c.comment_id, c.topic_id,
           sum(v.vote) as totals, sum(v.vote > 0) as yes, sum(v.vote < 0) as no,
           my_votes.vote as did_i_vote
    from comments c
    join users u on u.user_id = c.commenter_id
    left join votes v on v.comment_id = c.comment_id
    left join votes my_votes on my_votes.comment_id = c.comment_id
                                and my_votes.voter_id = 1
    where c.topic_id = 1
    group by c.comment_id, u.user_name, c.comment_id, c.topic_id, did_i_vote;
    

    更新:固定 group by 子句

    由 OP (tim peterson) 更新:将计数固定为总数并添加评论本身以由查询返回 final working SQLFiddle

    【讨论】:

    • 嗨@Olaf 谢谢!我唯一的问题是如何返回尚未投票的 cmets。我将 comment_id=4 添加到您的 SQLFiddle 中,但查询没有返回它。 sqlfiddle.com/#!2/b562a/1
    • @timpeterson 您必须将内连接更改为左连接。请参阅修改后的答案和 sqlfiddle。
    猜你喜欢
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多