首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >postgresql中的动态条件插入

postgresql中的动态条件插入
EN

Stack Overflow用户
提问于 2014-06-25 04:13:57
回答 1查看 1.8K关注 0票数 0

我正尝试在postgresql中定义一个条件插入,对一个超过3列的索引(这提供了唯一性)。我尝试遵循postgresql文档中的以下示例:

代码语言:javascript
复制
 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的选择,你想要阻止插入,你该如何实现呢?下面是我当前的(错误的)代码:

代码语言:javascript
复制
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中。我已经寻找了一段时间的答案,但还没有能够成功地调整任何东西来解决这个问题。

EN

回答 1

Stack Overflow用户

发布于 2014-06-25 04:27:04

代码语言:javascript
复制
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中,使用三重引号原始字符串更简单、更简洁

代码语言:javascript
复制
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
    );
"""
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24395458

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档