将数据插入到父表名称的子表中

时间:2014-04-09 11:11:14

标签: 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 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');

SQLFiddle

现在我需要将master01的一些相关行添加到child表中。我只输入字符串master01作为输入,而不是master_id。我有一个使用cross join的解决方案:

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

这有效,但我觉得应该有更容易的事情。我还有其他选择吗?

2 个答案:

答案 0 :(得分:1)

没有交叉连接

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)

答案 1 :(得分:0)

我最终使用pgScript

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