如何在mysql中从分数表中获得每场比赛的3个第一名?
我有下表:如何在mysql中从分数表中获得每场比赛的3个第一名?,mysql,sql,greatest-n-per-group,Mysql,Sql,Greatest N Per Group,我有下表: CREATE TABLE `score` ( `score_id` int(10) unsigned NOT NULL auto_increment, `user_id` int(10) unsigned NOT NULL, `game_id` int(10) unsigned NOT NULL, `thescore` bigint(20) unsigned NOT NULL, `timestamp` timestamp N
CREATE TABLE `score` (
`score_id` int(10) unsigned NOT NULL auto_increment,
`user_id` int(10) unsigned NOT NULL,
`game_id` int(10) unsigned NOT NULL,
`thescore` bigint(20) unsigned NOT NULL,
`timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`score_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
这是一个分数表,存储用户id和游戏id以及每个游戏的分数。
每场比赛前三名都有奖杯。
我有一个用户id,我想检查该特定用户是否从任何游戏中获得任何奖杯
我是否可以在不创建临时表的情况下创建此查询 没有测试它,但应该可以正常工作:
SELECT game_id, user_id
FROM score score1
WHERE (SELECT COUNT(*) FROM score score2
WHERE score1.game_id = score2.game_id AND score2.thescore > score1.thescore) < 3
ORDER BY game_id ASC, thescore DESC;
SELECT
*,
@position := @position + 1 AS position
FROM
score
JOIN (SELECT @position := 0) p
WHERE
user_id = <INSERT_USER_ID>
AND game_id = <INSERT_GAME_ID>
ORDER BY
the_score
在那里,您可以检查位置字段,看看它是否在1和3之间。一种更清晰的方法,并进行了半测试 其中A数量<3
您可以使用子查询而不是临时表。我希望获得每个游戏的前3名。此查询将提供all表的前3位。这不起作用,因为@position变量仅为结果集中的行计算,并且由于您的WHERE user_id=…,因此结果集中只有该用户的分数,“位置”列只会告诉你用户得分在该列表中的位置。询问者说我有一个用户id,我想检查…,所以我想他真的想要一个该用户的游戏和奖杯列表。但看起来你在给他提供一份用户ID列表。是的,这看起来不错。您只需要添加WHERE s1.user_id='blah',因为询问者已经有了他想要的特定用户id,而且这可能会使大型数据集的查询速度更快。
SELECT DISTINCT user_id
FROM
(
select s.user_id, s.game_id, s.thescore,
(SELECT count(1)
from scores
where game_id = s.game_id
AND thescore > s.thescore
) AS acount FROM scores s
) AS a
SELECT s1.*
FROM score s1 LEFT OUTER JOIN score s2
ON (s1.game_id = s2.game_id AND s1.thescore < s2.thescore)
GROUP BY s1.score_id
HAVING COUNT(*) < 3;
SELECT s1.*
FROM score s1 LEFT OUTER JOIN score s2
ON (s1.game_id = s2.game_id AND (s1.thescore < s2.thescore
OR s1.thescore = s2.thescore AND s1.score_id < s2.score_id))
GROUP BY s1.score_id
HAVING COUNT(*) < 3;
+----+-------------+-------+------+---------------+------+---------+------+------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+---------------------------------+
| 1 | SIMPLE | s1 | ALL | NULL | NULL | NULL | NULL | 9 | Using temporary; Using filesort |
| 1 | SIMPLE | s2 | ALL | PRIMARY | NULL | NULL | NULL | 9 | |
+----+-------------+-------+------+---------------+------+---------+------+------+---------------------------------+