我正在Postgres 9.6.3中尝试以下查询
INSERT INTO join_table ("table_1_id", "table_2_id") VALUES
(7, SELECT "id" from "table_2" where label='Foo Bar');
Run Code Online (Sandbox Code Playgroud)
这抛出 ERROR: syntax error at or near "SELECT" at character 94
我已经看到了插入语句工作中的嵌套选择的示例,其中仅插入被选择的内容。上面的查询是否可能?
尝试在子查询周围添加括号:
INSERT INTO join_table ("table_1_id", "table_2_id") VALUES
(7, (SELECT "id" from "table_2" where label='Foo Bar'));
Run Code Online (Sandbox Code Playgroud)
使用insert . . . select. values是不必要的:
INSERT INTO join_table (table_1_id, table_2_id)
SELECT y, "id"
FROM "table_2"
WHERE label = 'Foo Bar';
Run Code Online (Sandbox Code Playgroud)
这也允许您从另一个表中插入多行。