sql - 向 postgresql 插入唯一值

标签 sql sql-insert postgresql-9.3

我在 postgresql 中使用以下命令创建一个表。

CREATE TABLE someTable (
    id serial primary key,
    col1 int NOT NULL,
    col2 int NOT NULL,
    unique (col1, col2)
);

然后执行 2 个插入语句。
  • insert into someTable (col1,col2) values(1,11),(1,12);
    它的工作
  • insert into someTable (col1,col2) values(1,13),(1,14),(1,11);
    得到错误(key(col1,col2)=(1,11) 已经存在。

  • 但我只需要避免重复对。这怎么可能?

    我试试这个

    x86_64-pc-linux-gnu 上的 PostgreSQL 9.5.0,由 gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2 编译,64 位和 PostgreSQL 9.3 在 x86_64-pc-linux-gnu 上,由 gcc (Ubuntu 4.8. 2-19ubuntu1) 4.8.2,64 位

    但我有错误

    我不需要在执行两个语句后这样放置。
    (1,11),(1,12),(1,13),(1,14)
    

    最佳答案

    使用 postgresql 9.5(最新版本)

    使用这样的查询

    insert into someTable (col1,col2) values(1,13),(1,14),(1,11) ON CONFLICT DO NOTHING;
    


    它将避免重复而无需任何额外的代码行。

    关于sql - 向 postgresql 插入唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35130267/

    相关文章:

    mysql - 多个插入和选择到单个查询中

    sql - 检索一对多关系中的最高值

    MySQL将2个表中的数据合并到第3个表中

    mysql - 是否为 INSERT IGNORE ... SELECT 指定了插入顺序?

    postgresql - 在 Amazon ec2 linux 上更改 postgresql 9.3 数据库位置

    使用 IN 的 MySQL 条件更新

    mysql desc 对我不起作用

    mysql - 将值插入 MySQL 中另一个表的列

    postgresql - 空值的非选择性部分索引

    postgresql - 刷新物化 View : Concurrency, 事务行为