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

Sql 如何在插入查询中使用select查询的输出作为输入?,sql,postgresql,sql-insert,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) 我指的是仓库的分区表。 现在我想把它插入仓库。我使用下面的查询 postgr

我有以下两个表格:-

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

postgres=# select * from warehouse;
 id | name | district_id
----+------+-------------
(0 rows)
我指的是仓库的分区表。 现在我想把它插入仓库。我使用下面的查询

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...
但它给了我错误,如上所示。为什么我不能在insert查询中使用另一个select查询的结果,就像我在上面的查询中所做的那样? 我认为,我所做的是一个有效的场景。是否存在任何限制,使其无法成为有效案例

提前感谢。

试试:

insert into warehouse
(name, district_id)
select 'Ghodasar-WH',id from district where name = 'Ahmedabad';

{默认值|值({expression | DEFAULT}[,…])[,…] |查询}


因此,只需使用
查询
这里

Vao Tsun就有了使用
插入的正确答案。选择
(并适当地向上投票)

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

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

我并没有建议使用子查询,以避免子查询作为表达式返回多行,但现在我认为-也许您的方式更好,所以用户看到他有多行,而我的将默默地接受所有返回的行