我在我的网站上进行竞赛。每场比赛都可以有多个参赛作品我想根据得分检索最好的3个条目或更多(在抽奖的情况下)。得分计算为所有选票得分的总和。
这是SQLFiddle:http://sqlfiddle.com/#!9/c2480
表格ENTRY如下:
id contest_id
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
表ENTRY_VOTE如下:
id entry_id score
-- entry 1 has 20 votes (5+10+5)
1 1 5
2 1 10
3 1 5
-- entry 2 has 20 votes (10+10)
4 2 10
5 2 10
-- entry 3 has 25 votes (5+5+5+10)
6 3 5
7 3 5
8 3 5
9 3 10
-- entry 4 has 10 votes (10)
10 4 10
-- entry 5 has 25 votes (10+10+5)
11 5 10
12 5 10
13 5 5
-- entry 6 has 5 votes (5)
14 6 5
-- entry 7 has 50 votes (10+10+10+10+10)
15 7 10
16 7 10
17 7 10
18 7 10
19 7 10
-- entry 8 has 20 votes (10+10)
20 8 10
21 8 10
-- entry 9 has 5 votes (5)
22 9 5
结果应该是(带抽奖):
id (entry_id) contest_id score
7 1 50
3 1 25
5 1 25
1 1 20
2 1 20
8 1 20
我正在尝试以下查询:
select * from (
select entry.*, sum(score) as final_score from entry join entry_vote on
entry.entry_id = entry_vote.entry_id group by entry_id
) as entries
where final_score in (
select distinct(final_score) from (
select entry_id, sum(score) as final_score from entry_vote group by entry_id
) as final_scores order by final_score desc limit 3;
)
第一个子查询返回所有entry_vote得分总和的条目 第二个子查询返回前3个区分总和得分(50,25和20) 此查询返回错误。有什么不对,怎么解决?
答案 0 :(得分:0)
您可以通过以下代码
执行此操作SELECT entry_id, SUM(score) AS score FROM entry_vote GROUP BY entry_id ORDER BY score DESC LIMIT 3;
答案 1 :(得分:0)
以下是SQLFiddle链接:http://sqlfiddle.com/#!9/c2480/50/0
我设法通过使用连接而不是子查询来解决查询。 我在问题上发布的查询收到错误,因为第二个子查询正在完成";":
select distinct(final_score) from (
select entry_id, sum(score) as final_score from entry_vote group by entry_id
) as final_scores order by final_score desc limit 3;
解决这个问题,下一个错误将是子查询内的限制。 Mysql不支持它们。
最终查询是:
select * from (
select entry.*, sum(score) as score from entry
join entry_vote on entry.entry_id = entry_vote.entry_id where entry.contest_id = <CONTEST_ID> group by entry_id
) as entry_with_score join (
select distinct(score) as score from (
select sum(score) as score from entry_vote
join entry on entry_vote.entry_id = entry.id
join contest on audition.contest_id = contest.id where contest.id = <CONTEST_ID> group by entry_id
) as score_by_entry order by score desc limit 3
) as top_score on entry_with_score.score = top_score.score;
答案 2 :(得分:0)
SELECT entry_id,total
FROM
( SELECT x.*
, IF(@prev=total,@i,@i:=@i+1) i,@prev:=total prev
FROM
( SELECT entry_id
, SUM(score) total
FROM entry_vote
GROUP
BY entry_id
) x
, (SELECT @i:=0,@prev:=NULL)vars
ORDER
BY total DESC
) a
WHERE i <=3;