我有这两张桌子。我有当前的玩家id_player,我想选择这个玩家的所有游戏(id_player)和他的对手信息。当前玩家和对手玩家使用相同的id_game连接。或
table game:`id_game` (...)
table game_player:`id_game_player, id_player, id_game`(...)
“向我提供当前玩家及其对手的所有单独游戏信息 并加入他们的游戏信息(按游戏分组)“
结果为:
+---player game info
game1 |
+---opponent game info
+---player game info
game2 |
+---opponent1 game info
+---player game info
game2 |
+---opponent2 game info
任何人都可以提供MySQL解决方案吗?
谢谢
编辑: 我尝试使用这段代码,但我不确定这是最快的方法(WHERE IN),有没有办法对上面的结果进行分组?
SELECT * FROM game_player
JOIN `game` ON game.id_game = game_player.id_game
WHERE game_player.id_game
IN (
SELECT game_player.id_game
FROM `game_player`
WHERE game_player.id_player =2)
答案 0 :(得分:3)
试一试
SET @player_ID = 0; -- <<== the playerID
SELECT a.*, b.*, 'player' Status -- this is the first part of the union
FROM game a -- which gets all the game of
INNER JOIN game_player b -- the selected player and its info
ON a.id_game = b.id_game
WHERE id_player = @player_ID
UNION ALL
SELECT d.*, c.*, 'opponent' status
FROM game_player c
INNER JOIN
(
SELECT a.*
FROM game aa
INNER JOIN game_player bb
ON aa.id_game = bb.id_game
WHERE bb.id_player = @player_ID
) d ON c.id_game = d.id_game AND c.id_player <> @player_ID
ORDER BY id_game, status