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

时间:2018-04-04 11:01:54

标签: 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)

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

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...

但它给了我错误,如上所示。为什么我不能在插入查询中使用另一个选择查询的结果,就像我在上面的查询中所做的那样? 我想,我正在做的是一个有效的场景。是否有任何限制,以防止它出现在有效案件中?

提前致谢。

2 个答案:

答案 0 :(得分:4)

尝试:

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

https://www.postgresql.org/docs/current/static/sql-insert.html

  

{DEFAULT VALUES | VALUES({expression | DEFAULT} [,...])[,...]   |查询}

所以只需在这里使用query

答案 1 :(得分:4)

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

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

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