根据查询结果值更新 DO SET UPDATE 中的字段

问题描述 投票:0回答:1

我有以下疑问:

INSERT INTO table1 (
  col1,
  col2,
  col3
)
VALUES (
  %s,
  (SELECT id FROM table2 WHERE name = %s),
  %s,
)
ON CONFLICT (fk_id)
DO UPDATE SET
  col1 = %s,
  ***col2 = (SELECT id FROM table2 WHERE name = %s),***
  col3 = %s
WHERE EXISTS (
  SELECT 1 FROM table1 WHERE fk_id = %s
)
RETURNING id;

粗体/斜体星号导致“字符串文字错误”。但是当它被删除时,查询工作正常。有没有可能的方法可以从 DO SET UPDATE 子句中的另一个表获取值?

python postgresql psycopg2
1个回答
0
投票

您不需要在on conflict do update ....阶段

获取值
。你已经拥有它们了。当 Postgres 检测到冲突时,它会在插入行上创建一个图像,您可以像
excluded.
那样访问该图像,否则将语句完全保留为原样,它将变为:

INSERT INTO table1 (
  col1,
  col2,
  col3
)
VALUES (
  %s,
  (SELECT id FROM table2 WHERE name = %s),
  %s,
)
ON CONFLICT (fk_id)
DO UPDATE SET
  col1 = excluded.col1
  col2 = excluded.col2
  col3 = excluded.col3
WHERE EXISTS (
  SELECT 1 FROM table1 WHERE fk_id = %s
)
RETURNING id;
© www.soinside.com 2019 - 2024. All rights reserved.