使用 unnest 更新多个 postgresql 记录
Update multiple postgresql records using unnest
我有一个数据库 table,其中包含近 100 万条记录。
我添加了一个新列,名为 concentration
。
然后我有一个函数可以为每条记录计算 'concentration'。
现在,我想批量更新记录,所以我一直在看下面的questions/answers:, and ,但我不确定如何使用unnest
]...
这是我的 Python 3 函数来执行更新:
def BatchUpdateWithConcentration(tablename, concentrations):
connection = psycopg2.connect(dbname=database_name, host=host, port=port, user=username, password=password);
cursor = connection.cursor();
sql = """
update #tablename# as t
set
t.concentration = s.con
FROM unnest(%s) s(con, id)
WHERE t.id = s.id;
"""
cursor.execute(sql.replace('#tablename#',tablename.lower()), (concentrations,))
connection.commit()
cursor.close()
connection.close()
concentrations
是一个元组数组:
[(3.718244705238561e-16, 108264), (...)]
第一个值为双精度,第二个为整数,分别代表浓度和rowid。
我得到的错误是:
psycopg2.ProgrammingError: a column definition list is required for functions returning "record"
LINE 5: FROM unnest(ARRAY[(3.718244705238561e-16, 108264), (...
^
由于 Psycopg 将 Python 元组改编为 Postgresql 匿名记录,因此有必要指定数据类型:
from unnest(%s) s(con numeric, id integer)
我有一个数据库 table,其中包含近 100 万条记录。
我添加了一个新列,名为 concentration
。
然后我有一个函数可以为每条记录计算 'concentration'。
现在,我想批量更新记录,所以我一直在看下面的questions/answers:unnest
]...
这是我的 Python 3 函数来执行更新:
def BatchUpdateWithConcentration(tablename, concentrations):
connection = psycopg2.connect(dbname=database_name, host=host, port=port, user=username, password=password);
cursor = connection.cursor();
sql = """
update #tablename# as t
set
t.concentration = s.con
FROM unnest(%s) s(con, id)
WHERE t.id = s.id;
"""
cursor.execute(sql.replace('#tablename#',tablename.lower()), (concentrations,))
connection.commit()
cursor.close()
connection.close()
concentrations
是一个元组数组:
[(3.718244705238561e-16, 108264), (...)]
第一个值为双精度,第二个为整数,分别代表浓度和rowid。
我得到的错误是:
psycopg2.ProgrammingError: a column definition list is required for functions returning "record" LINE 5: FROM unnest(ARRAY[(3.718244705238561e-16, 108264), (... ^
由于 Psycopg 将 Python 元组改编为 Postgresql 匿名记录,因此有必要指定数据类型:
from unnest(%s) s(con numeric, id integer)