如何使用select查询的输出作为insert查询的输入? [英] How to use the output of select query as an input in the insert query?
问题描述
我有以下两个表:-
postgres=# select * from district;
id | name
----+-----------
1 | Ahmedabad
2 | Barmer
(2 rows)
postgres=# select * from warehouse;
id | name | district_id
----+------+-------------
(0 rows)
我指的是仓库的区表.现在我想插入到仓库中.我正在使用以下查询
I am referring district table from warehouse. Now I want to insert into warehouse. I am using following query
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...
但它给了我错误,如上所示.为什么我不能在插入查询中使用另一个选择查询的结果,就像我在上面的查询中所做的那样?我认为,我正在做的是一个有效的场景.是否有任何限制,使其无法成为有效案例?
But it gives me error, as shown above. Why I can't use the result of another select query in the insert query, as I am doing in above query ? I think, what I am doing is a valid scenario. Is there any limitations, that's preventing it from a valid case ?
提前致谢.
推荐答案
Vao Tsun 有使用 insert 的正确答案...选择
(并适当投票).
Vao Tsun has the correct answer for using insert . . . select
(and duly upvoted).
但是,您正在尝试在 values()
中使用子查询.这是允许的,但子查询需要它自己的括号.所以你的版本可以作为:
However, you are trying to use a subquery in values()
. That is allowed, but a subquery needs its own parentheses. So your version would work as:
insert into warehouse (name, district_id)
values ( 'Ghodasar-WH', (select id from district where name = 'Ahmedabad') );
这篇关于如何使用select查询的输出作为insert查询的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!