它是复杂的MySQL查询

时间:2010-03-31 16:26:51

标签: mysql

我有answers (ans_id,question_id,ans_date)和answers_votes (vote_id,user_id,ans_id,vote = 1或-1)。

如何选择今天发布的总和(投票)大的答案。这意味着今天的日期为 ans_date

2 个答案:

答案 0 :(得分: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点或更低。

答案 1 :(得分: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个得票最多的答案,并且今天已经创建了。

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


未经测试,因为我没有您的数据库 - 因此可能包含一些错误......