gpt4 book ai didi

sql - 避免在 SQL 插入中重复预定义的值

转载 作者:行者123 更新时间:2023-12-02 16:31:54 25 4
gpt4 key购买 nike

我希望插入与一对 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首先声明我的身份的声明:

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 组合的方法表。

最佳答案

您可以使用横向连接:

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);

关于sql - 避免在 SQL 插入中重复预定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63363653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com