INSERT INTO table1 (col1, col2) VALUES (SELECT col1, col2 FROM othertable)
Http://www.postgresql.org/docs/9.0/static/static/sql-update.html
)同点2似乎不起作用。我遇到以下错误:子查询必须仅返回一列。
UPDATE table1
SET col1 = othertable.col2,
col2 = othertable.col3
FROM othertable
WHERE othertable.col1 = 123;
对于插入
使用:
VALUES
语法。
MOMG小马的答案非常有效,但是如果您需要更复杂的东西,这里是一个稍微高级的更新查询的示例:UPDATE table1
SET col1 = subquery.col2,
col2 = subquery.col3
FROM (
SELECT t2.foo as col1, t3.bar as col2, t3.foobar as col3
FROM table2 t2 INNER JOIN table3 t3 ON t2.id = t3.t2_id
WHERE t2.created_at > '2016-01-01'
) AS subquery
WHERE table1.id = subquery.col1;
UPDATE table1 SET (col1, col2) = (col2, col3) FROM othertable WHERE othertable.col1 = 123;
始终最好先运行交易中的查询