2012-11-15 90 views
1

我正在開發一個評論系統,像Stackoverflow或Disqus有人可以在評論和投票評論。我有三個表格:USERS,COMMENTSVOTESStackoverflow-like評論投票SQL查詢

我無法弄清楚如何編寫查詢來計算投票並返回給定用戶是否投了票。每個用戶只能對每條評論投票一次,不能對自己的評論投票。此外,評論和投票不僅限於一個主題。每個頁面都有自己的主題,因此在執行GETSELECT評論和投票時,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 

回答

4

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; 

更新:固定組由子句

更新由OP(tim peterson):固定計數爲總計和a dded評論本身將被查詢返回 final working SQLFiddle

+0

嗨@Olaf謝謝!我唯一的問題是如何返回尚未投票的評論。我在你的SQLFiddle中添加了comment_id = 4,但它並沒有被查詢返回。 http://www.sqlfiddle.com/#!2/b562a/1 –

+0

@timpeterson您必須將內連接更改爲左連接。請參閱修改後的答案和sqlfiddle。 –

+0

甜美!現在我懂了!謝謝! –