【问题标题】:How to use the output of select query as an input in the insert query?如何在插入查询中使用选择查询的输出作为输入?
【发布时间】:2018-04-04 11:01:54
【问题描述】:

我有以下两个表:-

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

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

提前致谢。

【问题讨论】:

    标签: sql postgresql sql-insert


    【解决方案1】:

    Vao Tsun 有使用insert . . . select 的正确答案(并得到适当的支持)。

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

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

    【讨论】:

    • 我没有提出子查询,以避免可能用作表达式的子查询返回多行,但现在我认为 - 也许你的方式更好,所以用户看到他有多行,而我的会默默接受所有返回的行
    【解决方案2】:

    尝试:

    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

    { 默认值 |值 ( { 表达式 | 默认 } [, ...] ) [, ...] |查询}

    所以在这里使用query

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-29
      • 2015-09-12
      • 2014-09-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多