1

1)我需要:“查找所有玩相同游戏的玩家 '55' 对于游戏 id 大于 2”

表格如下图所示:

在此处输入图像描述

我尝试了很多语句,但它们产生了错误的结果:

SELECT Games.id, Players.id from Games, Players 
WHERE Players.id='55' and Games.id > 2;

2)另外,如果我说我需要选择与以前相同的选项,您会怎么做,其中“游戏的 id 只是降序排列的最后 2 个”(即在这种情况下,只有 id 为 3 和 4 的游戏,但这可能其他情况不同)。我只能想到将 Games.id 与用户输入的数字进行比较,但你们中的一些人可能知道另一种方式......

有人能帮助我吗?谢谢!

编辑

1)SELECT b.id_player, b.id_game FROM Players a, Players b WHERE a.id_player = '55' AND b.id_game = a.id_game AND b.id_player <> '55' AND a.id_game > 2;

2) 选项 1 适用于问题 1,但问题 2 需要一个对我不起作用的 TOP 子句。

我怎样才能使用 LIMIT 或 TOP 来达到相同的效果a.id_game > 2?我只想要最后 2 个 ID_GAME 的结果,在这种情况下是 id=3 和 id=4...

编辑: 没关系,我有第一个问题。我将把 LIMIT 设置为一个固定的数字。谢谢您的帮助

4

3 回答 3

1
SELECT Players.* 
FROM 
(SELECT id_game 
    FROM Players 
    WHERE id_player = 55 
    ORDER BY id_game DESC 
    LIMIT 2) 
AS A JOIN Players ON Players.id_game = A.id_game 
WHERE id_player <> 55

编辑。子查询中的限制在mysql中还没有实现(原帖),mysql本身的替代方案是使用这样的查询,这次测试。

于 2013-02-06T18:32:22.537 回答
1

你需要一个自我加入。我现在也无法测试这个 - 稍后会做一个 SQL 小提琴,但它应该是这样的:

SELECT b.id_player, b.id_game 
FROM Players a, 
     Players b 
WHERE a.id_player = '55' 
AND   b.id_game   = a.id_game 
AND   b.id_player <> '55' 
AND   a.id_game > 2
order by b.id_game
limit 2;
于 2013-02-06T18:57:04.530 回答
1

这肯定会奏效。

SELECT a.* FROM Players a 
INNER JOIN (SELECT id,id_player,id_game 
            FROM players 
            WHERE id_game > 2 AND id_player = 55
           ) b 
ON a.id_game = b.id_game
WHERE a.id_player != 55;
于 2013-02-06T19:50:07.963 回答