我是一名新手并试图将相关值同时插入两个表中。我很感激你的指导解决这个问题!
表1(球员):
CREATE TABLE players(
player_id serial PRIMARY KEY,
player_name varchar(50) NOT NULL);
表2(匹配):
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
);
我的功能: 我希望函数将值传递给查询。 我尝试了多种变体,包括以下但到目前为止没有运气。
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') """)
答案 0 :(得分:2)
我会这样做:
connection.begin() # start a transaction
cur.execute("INSERT INTO players (player_name) VALUES (%(name)s) RETURNING player_id", {'name': name})
player_id = cur.fetchone()[0]
cur.execute("INSERT INTO matches (player_id, match, match_result) VALUES (%(player_id)s, 1, 'won')", {'player_id': player_id})
connection.commit()
答案 1 :(得分:1)
在一个查询中执行此操作:
query = """
with player_key as (
insert into players(player_name)
values (%(name)s)
returning player_id
)
insert into matches (player_id, match, match_result)
select player_id, 1, 'won'
from player_key
"""
cursor.execute (query, {'name': name})