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

时间:2013-03-22 13:55:59

标签: 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 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

非常感谢任何有关此操作的实际语法的帮助!

1 个答案:

答案 0 :(得分:2)

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