我有两张表,Quiz
& Winners
Quiz Table:
id name pub_date type theme
1 bday quiz 2014-01-03 random fun
Winners Table:
id quizId winner points match_date
1 1 Nick 100 2016-02-29
2 1 Mick 156 2016-03-04
3 1 Sara 199 2016-03-06
-> `quizId` references to `id` in Quiz Table
我想要实现的目标是获得一个测验&它在单个html可排序表格行中的获胜者如下:
id name pub_date type theme 2016-03-06 2016-03-05 2016-03-04 ...
1 bday quiz 2014-01-03 random fun 199 156
我正在尝试这样的事情:
SELECT Quiz.id,Quiz.name,Quiz.pub_date,Quiz.type,Quiz.theme,Winners.winner
FROM Quiz,Winners
WHERE Quiz.id = Winners.quizId AND
Quiz.pub_date > '2015-03-01' AND
Quiz.pub_date < '2016-03-06' AND
Winners.match_date > '2016-02-01' AND
Winners.match_date < '2016-03-06'
ORDER BY Winners.points DESC
LIMIT 100
此方法效果很好,但LIMIT条件返回100行,而我需要100个测验&amp;他们的赢家也重复内容。
我想到的另一种方法是首先调用每个100个测验行。获得每个测验的获胜者,在这种情况下,我不能按优胜者的分数对测验进行排序。
答案 0 :(得分:1)
如果你想拥有100场比赛的所有获胜者:
SELECT *
FROM Quiz AS q
JOIN (
SELECT @rn:=@rn+1 AS rank, q2.id, z.p AS m, z.mp AS n
FROM Quiz AS q2
JOIN
( SELECT MAX(w.points) AS p, w.quizId AS mp
FROM Winners AS w
WHERE w.match_date BETWEEN '2013-03-01' AND '2016-03-06'
GROUP BY w.quizId
) AS z ON z.mp = q2.id, (SELECT @rn:=0) t2
) AS u ON u.id = q.id
JOIN Winners AS w2 ON w2.quizId = n
WHERE rank <= 2 AND m = points
工作示例:http://sqlfiddle.com/#!9/5c6d8/2
如果要将其更改为100。您需要修改rank <= 2
。
我只是想知道它适用于2个测验。
答案 1 :(得分:-1)
你可能想试试这个:
SELECT Quiz.id,Quiz.name,Quiz.pub_date,Quiz.type,Quiz.theme,Winners.winner
FROM Quiz as Quiz
INNER JOIN Winners as Winners ON Quiz.id = Winners.quizId
WHERE
Quiz.pub_date > '2015-03-01' AND
Quiz.pub_date < '2016-03-06' AND
Winners.match_date > '2016-02-01' AND
Winners.match_date < '2016-03-06'
GROUP BY Winners.id
ORDER BY Winners.points DESC
LIMIT 100
不确定此输出并且未检查代码
答案 2 :(得分:-3)
在选择后尝试使用addind distinct。它将消除所选行集的重复行。
SELECT distinct Quiz.id,Quiz.name,Quiz.pub_date,Quiz.type,Quiz.theme,Winners.winner
FROM Quiz,Winners
WHERE Quiz.id = Winners.quizId AND
Quiz.pub_date > '2015-03-01' AND
Quiz.pub_date < '2016-03-06' AND
Winners.match_date > '2016-02-01' AND
Winners.match_date < '2016-03-06'
ORDER BY Winners.points DESC
LIMIT 100