如何使用select查询的输出作为插入查询的输入?

Man*_*hit 1 sql postgresql sql-insert

我有以下两张表:-

postgres=# select * from district;
 id |   name
----+-----------
  1 | Ahmedabad
  2 | Barmer
(2 rows)

postgres=# select * from warehouse;
 id | name | district_id
----+------+-------------
(0 rows)
Run Code Online (Sandbox Code Playgroud)

我指的是仓库中的区表。现在我想插入仓库。我正在使用以下查询

postgres=# insert into warehouse
(name, district_id)
values
('Ghodasar-WH', select id from district where name = 'Ahmedabad');
ERROR:  syntax error at or near "select"
LINE 4: ('Ghodasar-WH', select id from district where name = 'Ahmeda...
Run Code Online (Sandbox Code Playgroud)

但它给了我错误,如上所示。为什么我不能在插入查询中使用另一个选择查询的结果,就像我在上面的查询中所做的那样?我认为,我正在做的事情是一个有效的场景。是否存在任何限制,导致其无法成为有效案例?

提前致谢。

Gor*_*off 5

Vao Tsun 有正确的使用答案insert . . . select(并正式投票)。

但是,您正在尝试在 中使用子查询values()。这是允许的,但子查询需要自己的括号。所以你的版本将工作为:

insert into warehouse (name, district_id)
    values ( 'Ghodasar-WH', (select id from district where name = 'Ahmedabad') );
Run Code Online (Sandbox Code Playgroud)

  • 我没有提出子查询,以避免可能的*用作表达式的子查询返回多于一行*,但现在我想 - 也许你的方法更好,所以用户看到他有多行,而我的会默默接受所有返回的行 (2认同)