简体   繁体   English

MySQL选择内部联接和联合

[英]MySQL select inner join and union

I have this two tables. 我有这两个表。 I have current player id_player, I want to select all games from this player (id_player) and his opponents info. 我当前有玩家id_player,我想从该玩家(id_player)及其对手信息中选择所有游戏。 Current player and opponent player are connected with same id_game. 当前玩家和对手玩家使用相同的id_game连接。 or 要么

桌子

table game:`id_game` (...)
table game_player:`id_game_player, id_player, id_game`(...)

"give me all separate game info from current player and his opponent and join info for their game (grouped by game)" “将当前玩家和他的对手的所有单独游戏信息提供给我,并加入他们游戏的信息(按游戏分组)”

result as: 结果为:

      +---player game info
game1 |
      +---opponent game info

      +---player game info
game2 |
      +---opponent1 game info

      +---player game info
game2 |
      +---opponent2 game info

Can anyone provide me MySQL solution? 谁能为我提供MySQL解决方案?

Thanks 谢谢


EDIT: I try with this code but I'm not sure this is fastest way (WHERE IN) and is there any way to group results like above? 编辑:我尝试使用此代码,但我不确定这是最快的方法(在何处),是否有任何方法可以对上述结果进行分组?

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)

give this a try 试试看

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM