I record sports data in three tables:
- matches (id, start_time)
- match_teams (id, match_id, team_id, score)
- match_players (id, match_id, team_id, player_id)
Each match consists of several teams, each team consists of several players (actually a list of lists). With team_id and player_id as foreign keys in the table of teams and players, respectively.
Using the structure above, I need to first insert into the match table and use the returned identifier to go to match_teams and match_players.
Following this question , I use the following CTE to accomplish this when I insert one match:
WITH a AS (INSERT INTO matches (start_time)
VALUES ('"0001-01-01T00:00:00+00:00"')
RETURNING id),
b AS (INSERT INTO match_teams (match_id, team_id, score)
VALUES
((SELECT id FROM a), 5, 1),
((SELECT id FROM a), 6, 2))
INSERT INTO match_players (match_id, team_id, player_id)
VALUES
((SELECT id FROM a), 5, 3),
((SELECT id FROM a), 5, 4),
((SELECT id FROM a), 6, 5)
((SELECT id FROM a), 6, 6);
. , /.
WITH a AS (INSERT INTO matches (start_time)
VALUES
('"0001-01-01T00:00:00+00:00"'),
('"0001-01-01T00:00:00+00:00"')
RETURNING id),
b AS (INSERT INTO match_teams (match_id, team_id, score)
VALUES
((SELECT id FROM a OFFSET 0 LIMIT 1), 5, 1),
((SELECT id FROM a OFFSET 0 LIMIT 1), 6, 2),
((SELECT id FROM a OFFSET 1 LIMIT 1), 5, 2),
((SELECT id FROM a OFFSET 1 LIMIT 1), 6, 1))
INSERT INTO match_players (match_id, team_id, player_id)
VALUES
((SELECT id FROM a OFFSET 0 LIMIT 1), 5, 3),
((SELECT id FROM a OFFSET 0 LIMIT 1), 6, 4),
((SELECT id FROM a OFFSET 1 LIMIT 1), 5, 5),
((SELECT id FROM a OFFSET 1 LIMIT 1), 6, 6);
, . ?
, . , , . " ?"