I am a newbie and have hit a road block trying to insert related values into two tables simultaneously. I would appreciate your guidance to solve this!
Table 1(players):
CREATE TABLE players(
player_id serial PRIMARY KEY,
player_name varchar(50) NOT NULL);
Table 2(matches):
CREATE TABLE matches(
player_id integer CONSTRAINT fk_links_match_player
REFERENCES players(player_id) NOT NULL,
match int NOT NULL,
match_result varchar(4) NOT NULL
);
My function: I want the function to pass values to the query. I have tried multiple variations including the following but no luck so far.
def registerPlayer(name):
cur.execute("""WITH player_key AS
(INSERT INTO players(player_name) VALUES(%(name)s), {'name': name} RETURNING player_id)
INSERT INTO matches (player_id, match, match_result)
VALUES((SELECT player_key.player_id), 1, 'won') """)
Do it in a single query: