Вопрос

I'm developing a commenting system like Stackoverflow or Disqus has where people can comment and vote on the comments. I have three tables for this: USERS, COMMENTS, and VOTES.

I'm having trouble figure out how to write the query to count votes and returning whether or not a given user has voted. Each user can only vote once per comment and can't vote on their own comment. Also, the comments and votes aren't just on one topic. Each page has its own topic and so when doing a GET to SELECT comments and votes, the WHERE topic_id='X' needs to be reflected in the query too.

here's my tables' data, how my query looks so far, and what i hope to have it return:

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
Это было полезно?

Решение

SQL Fiddle for playing

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;

Update: fixed group by clause

update by OP (tim peterson): fixed count as totals and added comment itself to be returned by the query final working SQLFiddle

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top