竞赛优胜者的Mysql查询,包括在另一个表中有分数的抽奖条目
我正在我的网站上举办比赛。每场比赛都可以有多个参赛作品。我想根据分数在抽签的情况下检索最好的3个或更多条目。分数计算为所有投票的分数之和 以下是SQLFiddle: 表格条目如下所示:竞赛优胜者的Mysql查询,包括在另一个表中有分数的抽奖条目,mysql,sql,Mysql,Sql,我正在我的网站上举办比赛。每场比赛都可以有多个参赛作品。我想根据分数在抽签的情况下检索最好的3个或更多条目。分数计算为所有投票的分数之和 以下是SQLFiddle: 表格条目如下所示: id contest_id 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1
id contest_id
1 1
2 1
3 1
4 1
5 1
6 1
7 1
8 1
9 1
下表所列项目如下:
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;
)
第一个子查询返回所有条目,所有条目的投票分数相加。
第二个子查询返回前三名的distincts总分50、25和20。
此查询返回错误。有什么问题以及如何解决?您可以通过以下代码来解决
SELECT entry_id, SUM(score) AS score FROM entry_vote GROUP BY entry_id ORDER BY score DESC LIMIT 3;
以下是SQLFIDLE链接: 我设法通过使用联接而不是子查询来解决查询。 我在问题上发布的查询出现错误,因为第二个子查询的结尾是;:
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;
我想要前三名的条目。我已经编辑了SQL,它会给你前三名的分数。不,你不明白这个问题。这个查询是错误的,因为限制为3只会带来50分和25分,但正确的是分数为50分、25分和20分的条目。您的脚本不起作用,因为这个版本的MySQL还不支持第二个结果的“LIMIT&IN/ALL/ANY/SOME subquery”,你想得到哪一个1=20,2=20,8=20就告诉我我可以写一个存储过程。我忘了添加带有竞赛id的where子句。将更新答案!
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;