[英]Mysql query for winners in the contest including draws entries having score in another table
我正在網站上舉辦比賽。 每個競賽可以有多個條目。 我想根據分數檢索最好的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)。
該查詢返回錯誤。 有什么問題,怎么解決?
您可以通過以下代碼執行此操作
SELECT entry_id, SUM(score) AS score FROM entry_vote GROUP BY entry_id ORDER BY score DESC LIMIT 3;
這是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;
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.