我希望插入与一对 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');
但我不想重复那些10
和20
。
前段时间我问了一个类似的问题(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
表结合起来的方法。