2

我希望插入与一对 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语句结合起来。我有这个不工作的查询,但这说明了我想要实现的目标:

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表结合起来的方法。

4

2 回答 2

3

您可以使用横向连接:

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);
于 2020-08-11T17:48:17.440 回答
3

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

do $$
DEFINE
    v_first_id  NUMBER := 10;
    v_second_id NUMBER := 20;
BEGIN
    ... Your Insert Statement ...
END; $$
于 2020-08-11T17:57:15.723 回答