PostgreSQL根据一次选择的结果向任何表中多次插入

时间:2018-12-17 12:12:41

标签: postgresql

使用Postgresql(9.6),我需要根据一个选择查询的结果对任何表( table1,table2,table3,... )执行多个插入查询如果结果有一个或多个记录,则从另一个 tableMain 中获取,例如:

{
 insert into table1 (id, name) values(1, 'name');
 insert into table2 (id, name) values(1, 'name');
 insert into table3 (id, name) values(1, 'name');
} if exists (select id from tableMain where id = 1)

1 个答案:

答案 0 :(得分:1)

您可以使用data modifying CTE首先检查tablemain中的行是否存在,然后重新使用该行,以导致随后的INSERT语句。

with idcheck (main_exist) as (
  select exists (select * from tablemain where id = 1 limit 1)
), t1 as (
  insert into table1 (id, name)
  select 1, 'name'
  from idcheck 
  where main_exists
), t2 as (
  insert into table2 (id, name)
  select 1, 'name'
  from idcheck 
  where main_exists
)
insert into table3 (id, name)
select 1, 'name'
from idcheck 
where main_exists;

如果您始终想在所有三个表中插入相同的值,则可以在第一个查询中包括这些值,这样就不必重复它们:

with idcheck (id, name, main_exist) as (
  select 1, 
         'name',
         exists (select * from tablemain where id = 1 limit 1)
), t1 as (
  insert into table1 (id, name)
  select id, name
  from idcheck 
  where main_exists
), t2 as (
  insert into table2 (id, name)
  select id, name
  from idcheck 
  where main_exists
)
insert into table3 (id, name)
select id, name
from idcheck 
where main_exists;