How to use the output of select query as an input in the insert query?

后端 未结 2 1092
春和景丽
春和景丽 2021-01-27 07:40

I have following two tables:-

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

postgres=# select * from wa         


        
相关标签:
2条回答
  • 2021-01-27 08:23

    Vao Tsun has the correct answer for using insert . . . select (and duly upvoted).

    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') );
    
    0 讨论(0)
  • 2021-01-27 08:23

    try:

    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 }

    so just use query here

    0 讨论(0)
提交回复
热议问题