MySQL 选择内部连接和联合

标签 mysql sql union inner-join

我有这两张表。我有当前玩家 id_player,我想从这个玩家 (id_player) 和他的对手信息中选择所有游戏。当前玩家和对手玩家连接同一个 id_game。或

tables

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)"

结果为:

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

最佳答案

试一试

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

关于MySQL 选择内部连接和联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14710107/

相关文章:

sql-server - 如何查找数据库中使用 UNION 的所有对象

mysql - 从 2 联合 sql 语句中获取不同的记录

java - 将 jOOQ 与 Google Cloud SQL 结合使用

mysql - 我正在尝试在 mysql 中设置一个表,但不断出现错误并且无法找出修复它的正确方法

sql - Project.params 中的 ODBC 连接SSIS

mysql - 使用其他行的 SUM() 和 COUNT() 更新一行

mysql union 没有按预期工作

mysql - 数据库复制 : multiple geographical locations with local database, 一个主远程数据库

php mysql 字段名称为<th>?

MySQL 查找缺失的评级