在psql中使用将相关数据插入到两个表中
Inserting related data into two tables using in psql
我是新手,在尝试将相关值同时插入两个表时遇到了障碍。非常感谢您的指导来解决这个问题!
Table 1(玩家):
CREATE TABLE players(
player_id serial PRIMARY KEY,
player_name varchar(50) NOT NULL);
Table 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') """)
我会这样做:
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()
在单个查询中完成:
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})
我是新手,在尝试将相关值同时插入两个表时遇到了障碍。非常感谢您的指导来解决这个问题!
Table 1(玩家):
CREATE TABLE players(
player_id serial PRIMARY KEY,
player_name varchar(50) NOT NULL);
Table 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') """)
我会这样做:
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()
在单个查询中完成:
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})