[英]Dynamic conditional insert in postgresql
我試圖在3列以上的索引上定義條件插入(在PostgreSQL中)(這賦予了唯一性)。 我正在嘗試從PostgreSQL文檔中遵循以下示例:
INSERT INTO example_table
(id, name)
SELECT 1, 'John'
WHERE
NOT EXISTS (
SELECT id FROM example_table WHERE id = 1
);
對於基本的SELECT WHERE NOT EXISTS結構。 但是,如果索引有所不同,即如果表中存在當前預插入行的id = index值的表中存在選擇項,那么您要防止插入,您如何實現此目的? 這是我當前的(錯誤的)代碼:
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中。 我已經搜索了一段時間了,但是還沒有能夠成功地使任何東西適應這個問題。
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
);
"""
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.