2010-03-31 149 views
0

我有一個answers(ans_id,question_id,ans_date)和answers_votes(vote_id,USER_ID,ans_id,表決= 1或-1)。複雜MySQL查詢它是

我該如何從答案中選擇有大總和(投票)今天發佈的投票。這意味着今天的日期在ans_date

+1

嗯......第二個問題就像今天這樣。家庭作業也許? 你到目前爲止嘗試過什麼?這裏有一個類似的問題:http://stackoverflow.com/questions/2553776/mysql-join-problem – itsmatt 2010-03-31 16:33:07

回答

2
select a.ans_id 
    , a.question_id 
    , a.ans_date 
    , (select sum(vote) from answers_votes where ans_id = a.ans_id) as points 
    , (select count(*) from answers_votes where ans_id = a.ans_id and vote = 1) as up_votes 
    , (select count(*) from answers_votes where ans_id = a.ans_id and vote = -1) as down_votes 
    from answers a 
where date(a.ans_date) = date(now()) 
order by points desc 

雖然現在這將使該points值有些多餘。它可以像計算up_votes - down_votes一樣計算 - 只要投票總是隻值1分或上下。

+0

你可以計算ans那個toke -1和ans那個toke 1 – 2010-03-31 16:51:12

+0

請幫助我知道-1個點的數量和1 – 2010-03-31 17:16:54

+1

已更新來顯示這些計數 – 2010-03-31 17:34:57

1

事情是這樣的:

select answers.ans_id, count(*) as nb_votes 
from answers 
    inner join answers_votes on answers_votes.ans_id = answers.ans_id 
where answers.ans_date = curdate() 
group by answers.ans_id 
order by count(*) desc 
limit 10 

應該給你10個回答說有得票最多,而今天已經創建了。

如果您需要更多或更少的10,您可以更改limit子句中的值。


沒有測試過,因爲我沒有你的數據庫 - 因此可能包含了一些錯誤......

+0

對於聚合函數使用COUNT(answers_votes)會給你票數。使用SUM(answers_votes.vote)來獲得投票的權重,因爲answers_votes.vote可以是+1或-1。 – 2010-03-31 16:57:39

+0

你可以寫完整的查詢 – 2010-03-31 17:06:21