如何连接三个表以一次性获取所有数据?

时间:2017-09-29 13:51:41

标签: sql postgresql

我有比赛,球队和球员(沙滩排球)。一场比赛由两队(teamA和teamB)组成。一支球队由两名球员(球员A和球员B)组成。

CREATE TABLE IF NOT EXISTS players (
    uuid        uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    created_at  timestamp NOT NULL DEFAULT NOW(),
    user_id     integer REFERENCES users,
    first_name  text,
    last_name   text
)

CREATE TABLE IF NOT EXISTS teams (
    uuid            uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    created_at      timestamp NOT NULL DEFAULT NOW(),
    user_id         integer REFERENCES users,
    player_1_uuid   uuid REFERENCES players,
    player_2_uuid   uuid REFERENCES players
)

CREATE TABLE IF NOT EXISTS matches (
    uuid        uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    created_at  timestamp NOT NULL DEFAULT NOW(),
    user_id     integer REFERENCES users,
    name        text,
    team_a_uuid uuid REFERENCES teams,
    team_b_uuid uuid REFERENCES teams
)

现在,我想通过针对给定user_id的单个请求获取所有匹配数据。到目前为止我已经尝试了

    SELECT
        matches.uuid, matches.created_at, matches.name,
        teams.uuid, teams.created_at,
        players.uuid, players.created_at, players.first_name, players.last_name
    FROM matches
    LEFT JOIN teams ON matches.team_a_uuid = teams.uuid
    LEFT JOIN teams ON matches.team_b_uuid = teams.uuid
    LEFT JOIN players ON teams.player_1_uuid = players.uuid
    LEFT JOIN players ON teams.player_2_uuid = players.uuid
    WHERE user_id = $1

这并没有给我所有四名球员(每队两名队员和每场比赛两队)。

任何提示?

2 个答案:

答案 0 :(得分:0)

您只需要加入每个表一次,但要概括您的条件,以便其中任何一个ID匹配:

SELECT
    matches.uuid, matches.created_at, matches.name,
    teams.uuid, teams.created_at,
    players.uuid, players.created_at, players.first_name, players.last_name
FROM matches
LEFT JOIN teams ON teams.uuid IN (matches.team_a_uuid, matches.team_b_uuid)
LEFT JOIN players ON players.uuid IN (teams.player_1_uuid, teams.player_2_uuid)
WHERE user_id = $1

答案 1 :(得分:0)

我认为你正在寻找这个结果

SELECT matches.* , 
  team_a.* ,  team_a_player_1.* , team_a_player_2.* , 
  team_b.* ,  team_b_player_1.* , team_b_player_2.*  
FROM matches    
    LEFT JOIN teams as team_a ON matches.team_a_uuid = team_a.uuid
    LEFT JOIN players as team_a_player_1 ON team_a_player_1.uuid = team_a.player_1_uuid
    LEFT JOIN players as team_a_player_2 ON team_a_player_2.uuid = team_a.player_2_uuid
    LEFT JOIN teams as team_b ON matches.team_b_uuid = team_b.uuid
    LEFT JOIN players as team_b_player_1 ON team_b_player_1.uuid = team_b.player_1_uuid
    LEFT JOIN players as team_b_player_2 ON team_b_player_2.uuid = team_b.player_2_uuid