【问题标题】:Postgresql Multiple insertions into any tables depending on result of one selectPostgresql 根据一次选择的结果多次插入任何表
【发布时间】:2019-05-17 19:22:24
【问题描述】:

使用 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)

【问题讨论】:

    标签: postgresql


    【解决方案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;
    

    【讨论】:

    • 这有帮助。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2012-11-08
    • 2019-05-26
    • 2017-11-28
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    相关资源
    最近更新 更多