【问题标题】:Joining two tables and two junction tables连接两个表和两个连接表
【发布时间】:2023-04-09 01:54:01
【问题描述】:

我有这些表:

  • 游戏(game_id、game_name 等)
  • 团队(teams_id、team_name 等)
  • 玩家(players_id、player_name 等)

联结表:

  • games_teams (game_id,teams_id)
  • teams_players (teams_id, player_id)

基本上每场比赛我都想查看球队的数量和球员的数量。

游戏名称 - 队伍数量 - 玩家数量

使用内部连接,我设法与团队一起加入游戏,但不能与玩家一起加入游戏。我相信它涉及多个 select 语句?

【问题讨论】:

    标签: mysql sql join select junction-table


    【解决方案1】:

    您可以在games_teams 联结表的帮助下加入gamesteams。然后,您可以通过teams_players 加入,以获取玩家 ID。请注意,对于此查询,您甚至不需要 players 表,因为您只需要它们的编号:

    SELECT   game_name, 
             COUNT(DISTINCT gt.team_id) AS number_of_teams,
             COUNT(DISTINCT tp.player_id) AS number_of_players
    FROM     games g
    JOIN     games_teams gt on g.game_id = gt.game_id
    JOIN     teams t ON gt.team_id = t.team_id
    JOIN     teams_players tp ON t.team_id = tp.team_id
    GROUP BY game_name
    

    【讨论】:

    • 谢谢你!!工作,但我改为左连接。花 3 个小时在这上面!
    猜你喜欢
    • 1970-01-01
    • 2016-12-09
    • 2016-11-18
    • 1970-01-01
    • 2011-04-27
    • 2012-02-28
    • 2011-04-07
    相关资源
    最近更新 更多