Postgresql 以主表的名称将数据插入子表
我有两个具有1…0.n关系的表:Postgresql 以主表的名称将数据插入子表,postgresql,Postgresql,我有两个具有1…0.n关系的表: --drop table if exists child; --drop table if exists master; create table master ( master_id serial primary key, master_name varchar, constraint unique_master unique (master_name) ); create table child ( child_id serial p
--drop table if exists child;
--drop table if exists master;
create table master (
master_id serial primary key,
master_name varchar,
constraint unique_master unique (master_name)
);
create table child (
child_id serial primary key,
master_id integer references master (master_id),
child_name varchar
);
在master
表中,我有两行:
insert into master (master_name) values ('master01');
insert into master (master_name) values ('master02');
现在我需要将master01
的一些相关行添加到child
表中。我只有字符串master01
作为输入,没有master\u id
。我有一个使用交叉连接的解决方案:
insert into child (master_id, child_name)
select
master_id, child_name
from
(select master_id from master where master_name = 'master01') as master_data
cross join (
values
('child01'),
('child02'),
('child03')
) child_data (child_name);
这是可行的,但我觉得应该有更简单的方法。我还有什么其他选择?没有交叉连接
insert into child (master_id, child_name)
select
(select master_id from master where master_name = 'master01'),
child_name
from (values
('child01'),
('child02'),
('child03')
) child_data (child_name)
我最终使用了:
您认为在我的查询中,会为每一行计算subselect吗?你测试过了吗?我猜它只会被评估一次,因此它的行为将与您的脚本完全相同。为什么要引入依赖关系?@ClodoaldoNeto你为我的问题提供了完美的答案,这就是它被接受的原因。使用pgScript简化了我的脚本,这比我问题中的示例复杂得多。由于我是脚本的唯一用户,并且它只在我的桌面上运行,而且我一直在使用pgAdmin,所以我不介意引入这种依赖关系。
SET @MN = select master_id from master where master_name = 'master01';
insert into child (master_id, child_name) values
(@MN, 'child01'),
(@MN, 'child02'),
(@MN, 'child03')