从 PostgreSQL 中的子查询更新或插入(多行和列)
我正在尝试在 postgres 中执行类似的操作:
UPDATE table1 SET (col1, col2) = (SELECT col2, col3 FROM othertable WHERE othertable.col1 = 123);
INSERT INTO table1 (col1, col2) VALUES (SELECT col1, col2 FROM othertable)
但即使使用 postgres 9.0 中提到的第 1 点也是不可能的文档(http://www.postgresql.org/docs/9.0/static /sql-update.html)
另外第2点似乎不起作用。我收到以下错误:子查询必须仅返回一列。
希望有人能为我找到解决方法。否则查询将花费大量时间:(。
仅供参考:我试图从多个表中选择不同的列并将它们存储到临时表中,以便另一个应用程序可以轻松获取准备好的数据。
I'm trying to do something like this in postgres:
UPDATE table1 SET (col1, col2) = (SELECT col2, col3 FROM othertable WHERE othertable.col1 = 123);
INSERT INTO table1 (col1, col2) VALUES (SELECT col1, col2 FROM othertable)
But point 1 is not possible even with postgres 9.0 as mentioned in the docs (http://www.postgresql.org/docs/9.0/static/sql-update.html)
Also point 2 seems not working. i'm getting the following error: subquery must return only one column.
Hope somebody has a workaround for me. otherwise the queries will take a looot of time :(.
FYI: I'm trying to select different columns from several tables and store them into a temporary table, so that another application can easily fetch the prepared data.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
OMG Ponies 的答案非常有效,但以防万一您需要更复杂的东西,这里是一个稍微更高级的更新查询的示例:
OMG Ponies's answer works perfectly, but just in case you need something more complex, here is an example of a slightly more advanced update query:
对于 UPDATE
用途:
对于 INSERT
用途:
如果您使用 SELECT 来填充 INSERT 值,则不需要
VALUES
语法。For the UPDATE
Use:
For the INSERT
Use:
You don't need the
VALUES
syntax if you are using a SELECT to populate the INSERT values.