如果表A不包含该值,则将PostgreSQL插入表A和表B

如果表A不包含该值,则将PostgreSQL插入表A和表B,postgresql,syntax,insert,Postgresql,Syntax,Insert,您好,我正在尝试在postgreSql表中执行以下操作,但语法有问题 伪代码: if (tableA.column1 does not contain value1) { INSERT INTO tableA (column1, column2) VALUES value1, value2 } // do this check even if the above already existed if (tableB does not contain value1 and val

您好,我正在尝试在postgreSql表中执行以下操作,但语法有问题

伪代码:

if (tableA.column1 does not contain value1)
{
    INSERT INTO tableA (column1, column2)
    VALUES value1, value2
}

// do this check even if the above already existed
if (tableB does not contain value1 and value3 in the same row)
{
    // it is ok if value1 and value3 already exist in the table, just not the same row
    INSERT INTO tableB (column1, column2)
    VALUES (value1, value3)
}

return true

如果您能提供此操作的实际语法方面的任何帮助,我们将不胜感激

我不明白第一个条件和第二个条件如何“属于”在一起。你可以独立运行这两个程序。有趣的是,现在我看到了,你的观点很有道理!请记住锁定表,或者准备好处理由于多个事务同时检查和插入同一记录而导致的错误(如果唯一)或重复(如果不唯一)。@CraigRinger:为什么要锁定?仅仅包装成一个事务还不够吗?@mvp如果你知道没有其他人会同时执行
insert
ing,是的。但是如果你知道你知道锁也不会花任何钱。插入不会相互阻塞。如果在两个并发插入之间共享一个唯一的密钥,则两个都将
选择
,并看到该密钥不存在,则两个都将尝试插入该密钥。一个将获胜,另一个将无法提交,并出现重复密钥错误,尽管无法看到冲突行。如果没有唯一的键,那么可见性规则将导致既看不到另一个正在插入的行,也看不到两个插入的行。
-- first insert:
insert into tablea (col1, col2)
select 1,2
from tablea
where not exists (select * from tablea where col1 = 1);

-- second insert (same logic to apply a conditional insert)
insert into tableb (col1, col2)
select 1,2
from tableb
where not exists (select * from tableb where col1 = 1 and col2 = 2);