我有以下表:

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;  

这是一个得分表存储USER_ID和game_id和每个游戏的得分。 有每场比赛的前3位奖杯。 我有一个user_ID的,我想,以检查是否是特定用户从任何游戏有任何奖杯。

我可以不用创建临时表以某种方式创建此查询?

有帮助吗?

解决方案

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;

该查询返回的行,所有赢得比赛。虽然关系包括;如果分数10,16,16,16,18则有四个赢家:16,16,16,18。我不知道你是如何处理的。你需要一些方法来解决连接条件的关系。

例如,如果联系受到了前面比赛获胜的决心,那么你可以修改查询是这样的:

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;

您也可以使用timestamp列,以解决关系,如果你能依靠它是UNIQUE

然而,MySQL的倾向于创建临时表用于这种类型的查询的反正。下面是EXPLAIN的此查询的输出:

+----+-------------+-------+------+---------------+------+---------+------+------+---------------------------------+
| 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 |                                 | 
+----+-------------+-------+------+---------------+------+---------+------+------+---------------------------------+

其他提示

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;

一个更明确的方式做到这一点,和semitested。

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
     

WHERE acount <3

Didn't测试,但应很好地工作:

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

有可以检查位置字段,看是否it's和3之间1。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top