我正尝试在postgresql中定义一个条件插入,对一个超过3列的索引(这提供了唯一性)。我尝试遵循postgresql文档中的以下示例:
INSERT INTO example_table
(id, name)
SELECT 1, 'John'
WHERE
NOT EXISTS (
SELECT id FROM example_table WHERE id = 1
);对于基本的选择WHERE NOT EXISTS结构。但是如果索引变化了,也就是说,如果表中有一个id=index值为current pre-insert row的选择,你想要阻止插入,你该如何实现呢?下面是我当前的(错误的)代码:
insert = (
"INSERT INTO table (index,a,b,c,d,e)"
"SELECT * FROM table WHERE NOT EXISTS (SELECT * FROM table WHERE index=index)");
cur.execute(insert,data)为了清楚起见,索引定义在数据列(a,b,c)上,数据是一行(index,a,b,c,d,e),我将其包装在psycopg2中。我已经寻找了一段时间的答案,但还没有能够成功地调整任何东西来解决这个问题。
发布于 2014-06-25 04:27:04
insert into t1 (a, b, c, d, e)
select a, b, c, d, e
from t2
where not exists (
select 1
from t1
where a = t2.a and b = t2.b and c = t2.c
);在Python中,使用三重引号原始字符串更简单、更简洁
insert = """
insert into t1 (a, b, c, d, e)
select a, b, c, d, e
from t2
where not exists (
select 1
from t1
where a = t2.a and b = t2.b and c = t2.c
);
"""https://stackoverflow.com/questions/24395458
复制相似问题