我的PostgreSQL数据库中有两个表: table1和table2。它们都包含一个id列。我想从table2添加一列,比如col1,添加到table1 where table1.id = table2.id。
我正在尝试通过SQLalchemy对此进行加点。我一直收到以下错误:
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.SyntaxError) syntax error at or near "INNER"以下是代码片段:
engine = create_engine(...)
with engine.connect() as con:
con.execute("ALTER TABLE table1 ADD COLUMN col1 text")
con.execute("UPDATE table1 \
INNER JOIN table2 ON table1.id = table2.id \
SET table1.col1 = table2.col1")为什么我会得到这个错误?
发布于 2020-07-10 00:24:54
PostgreSQL不像MySQL和MS Access那样支持UPDATE...JOIN。然而,Postgres甚至支持UPDATE...FROM...JOIN,也支持UPDATE...FROM
con.execute("""UPDATE table1 t1
SET col1 = t2.col1
FROM table2 t2
WHERE t1.id = t2.id""")发布于 2020-07-10 00:20:26
在postgres中更新时,您不能直接使用joins,并且您的joins方式是不正确的。请使用以下查询,
update table1 set table1.col1 = qry.col1
from
(select col1 from table2) qry
where
table1.id = table2.qry;发布于 2020-07-10 00:21:45
这不是update的正确语法。请参阅https://www.postgresql.org/docs/current/sql-update.html
update table1
set col1 = table2.col1
from table2
where table2.id = table1.id;https://stackoverflow.com/questions/62819242
复制相似问题