【问题标题】:Avoid repeating predefined value in SQL insert into避免在 SQL 插入中重复预定义的值
【发布时间】:2020-12-01 10:37:18
【问题描述】:

我希望插入与一对 id 相关联的几个值,而无需在查询中对这些 id 进行硬编码。
更具体地说,我有这张表foo

create table if not exists foo(id int, val text);

我可以通过以下方式插入我的值:

insert into foo
values
  (10, 'qwe_1'),
  (10, 'qwe_2'),
  (10, 'qwe_3'),
  (20, 'qwe_2'),
  (20, 'asd_3'),
  (20, 'asd_4');

但我不想重复那些1020

不久前我问了一个类似的问题 (SQL - Using WITH to declare variable on INSERT INTO),但它并没有解决我的问题。 我也无法理解如何使用INSERT repeating values in SQL 中建议的连接或类似方法,因为我想为每个 id 添加的值列表是任意的。


虽然不是绝对需要,但我想使用 with 语句首先声明我的 ID:

with c (first_id, second_id) as (values (10, 20))
select * from c;

但我不明白如何将它与insert into 语句结合起来。我有这个 non working 查询,但这说明了我想要实现的目标:

with c (first_id, second_id) as (values (10, 20))
insert into foo
values
  (c.first_id, 'qwe_1'),
  (c.first_id, 'qwe_2'),
  (c.first_id, 'qwe_3'),
  (c.second_id, 'qwe_2'),
  (c.second_id, 'asd_3'),
  (c.second_id, 'asd_4')
from c;

我的理解是values (...), ... 语句返回一个表,所以我可能缺少一种将这个表与c 表结合起来的方法。

【问题讨论】:

    标签: sql postgresql sql-insert lateral-join


    【解决方案1】:

    您可以使用横向连接:

    insert into foo (id, val)
        select v.id, v.val
        from (values (10, 20)) c(first_id, second_id) cross join lateral
             (values (c.first_id, 'qwe_1'),
                     (c.first_id, 'qwe_2'),
                     (c.first_id, 'qwe_3'),
                     (c.second_id, 'qwe_2'),
                     (c.second_id, 'asd_3'),
                     (c.second_id, 'asd_4')
             ) v(id, val);
    

    【讨论】:

      【解决方案2】:

      如果您能够使用块结构,我会使用该路线。

      do $$
      DEFINE
          v_first_id  NUMBER := 10;
          v_second_id NUMBER := 20;
      BEGIN
          ... Your Insert Statement ...
      END; $$
      

      【讨论】:

      • 这看起来有点简单,我设法让它使用以下查询:``` do $$ DECLARE v_first_id integer := 10; v_second_id 整数:= 20; BEGIN 插入 foo 值 (v_first_id, 'qwe_1'), (v_first_id, 'qwe_2'), (v_first_id, 'qwe_3'), (v_second_id, 'qwe_2'), (v_second_id, 'asd_3'), (v_second_id, 'asd_4 ');结尾; $$ 语言 plpgsql ```
      猜你喜欢
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多