【问题标题】:PostgreSQL INSERT based on SELECT results using PythonPostgreSQL INSERT 基于使用 Python 的 SELECT 结果
【发布时间】:2015-09-24 00:24:47
【问题描述】:

过去一周我一直在尝试解决这个问题,但一直无法解决。我有一个 PostgreSQL 数据库,可以跟踪在锦标赛中进行比赛的球员。我正在开发一个报告匹配结果的函数。它报告匹配结果的方式是简单地更新数据库(我现在不担心实际的报告系统)。

这是执行报告的函数:

def reportMatch(winner, loser):
"""Records the outcome of a single match between two players.

Args:
  winner:  the id number of the player who won
  loser:  the id number of the player who lost
"""
connection = connect()
cursor = connection.cursor()
match_played = 1

insert_statement = "INSERT INTO matches (winner_id, loser_id) VALUES (%s, %s)"
cursor.execute(insert_statement, (winner, loser))
cursor.execute("INSERT INTO players (match_count) VALUES (%s) SELECT players.id FROM players where (id = winner)" (match_played,)) # here is where I have my issue at runtime
connection.commit()
cursor.execute("INSERT INTO players(match_count) SELECT (id) FROM players VALUES (%s, %s)",(match_played, loser,))
connection.commit()
connection.close

我在上面注释掉的那一行是我得到错误的地方。更准确地指出:cursor.execute("INSERT INTO players(match_count) VALUES (%s) SELECT (id) FROM players WHERE (id = %s)",(match_played, winner,))

给出的错误如下:

reportMatch 中的文件“/vagrant/tournament/tournament.py”,第 103 行 cursor.execute(insert_statement_two, (match_played, 获胜者)) psycopg2.ProgrammingError:“SELECT”处或附近的语法错误 LINE 1: INSERT INTO player(match_count) VALUES (1) SELECT (id) FROM...

如果有帮助,这是我的架构:

CREATE TABLE players (
  id serial PRIMARY KEY,
  name varchar(50),
  match_count int DEFAULT 0,
  wins int DEFAULT 0,
  losses int DEFAULT 0,
  bye_count int
);

CREATE TABLE matches (
  winner_id serial references players(id),
  loser_id serial references players(id),
  did_battle BOOLEAN DEFAULT FALSE,
  match_id serial PRIMARY KEY
);

我对 MySQL 数据库有一些经验,但对 PostgreSQL 还是很陌生。我花了很多时间在网上寻找指南和教程,但运气不佳。任何帮助将不胜感激!

【问题讨论】:

    标签: python database postgresql


    【解决方案1】:

    您不能在INSERT 语句中既指定VALUES 又使用SELECT。这是一个或另一个。

    请参阅 Postgres 文档中INSERT 的定义了解更多详情。

    您也不需要指定id 值,因为serial 是一个特殊序列。

    该行在INSERT 字符串之后也缺少逗号。

    为了指定特定值,您可以使用WHERE 缩小SELECT 的范围,和/或利用早期INSERTs 中的RETURNING,但具体情况将取决于您的具体方式想把它们联系在一起。 (我不太确定你在从上面的代码中将表格链接在一起的目的是什么。)

    我怀疑使用RETURNINGplayers 获取2 个ID,这些ID 是INSERTed,然后在INSERT 中使用这些ID 到matches 符合您想要做的事情。

    【讨论】:

    • 迂腐吹毛求疵:实际上,您可以,因为VALUES 可以在子查询中使用。 INSERT INTO sometable(somecol) SELECT n FROM (VALUES (1),(2),(3)) x(n)。我什至发现了需要这样做的时候。
    • 啊,直到。很高兴知道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    相关资源
    最近更新 更多