跨越3個表插入多個行中1次的查詢我記錄運動在3代表的形式匹配數據:使用返回的ID
- 匹配(ID,START_TIME)
- match_teams(ID ,match_id,TEAM_ID,得分)
- match_players(ID,match_id,TEAM_ID,player_id)
每場比賽由幾支球隊組成,每支球隊由幾名球員組成(實際上是一份列表)。將team_id和player_id分別作爲球隊和球員表上的外鍵。
使用上述結構,我需要先插入匹配的表,然後使用返回的id傳入match_teams和match_players。
繼this question我使用下面的CTE做到這一點我在哪裏插入一個匹配:
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);
我想一次在一個查詢中插入多場比賽。我使用偏移和限制來爲球員/球隊選擇正確的比賽ID。
WITH a AS (INSERT INTO matches (start_time)
VALUES
('"0001-01-01T00:00:00+00:00"'), -- 1st match
('"0001-01-01T00:00:00+00:00"') -- 2nd match
RETURNING id),
b AS (INSERT INTO match_teams (match_id, team_id, score)
VALUES
((SELECT id FROM a OFFSET 0 LIMIT 1), 5, 1), -- 1st match
((SELECT id FROM a OFFSET 0 LIMIT 1), 6, 2), -- 1st match
((SELECT id FROM a OFFSET 1 LIMIT 1), 5, 2), -- 2nd match
((SELECT id FROM a OFFSET 1 LIMIT 1), 6, 1)) -- 2nd match
INSERT INTO match_players (match_id, team_id, player_id)
VALUES
((SELECT id FROM a OFFSET 0 LIMIT 1), 5, 3), -- 1st match
((SELECT id FROM a OFFSET 0 LIMIT 1), 6, 4), -- 1st match
((SELECT id FROM a OFFSET 1 LIMIT 1), 5, 5), -- 2nd match
((SELECT id FROM a OFFSET 1 LIMIT 1), 6, 6); -- 2nd match
這有效,但它似乎有點哈克解決方案。有沒有最佳實踐方法來做到這一點?
更新我意識到我有一些冗餘列。我已經解決了這個問題,但我認爲它不會顯着改變這個問題。我的問題更像是「像這種最佳實踐一樣使用偏移和限制?」
你可以使用序列(NEXTVAL,CURRVAL),以避免與'offset'那些'selects'。雖然我很確定這個查詢解決方案根本不是最佳實踐。 –