【问题标题】:insert unique values to postgresql向 postgresql 插入唯一值
【发布时间】:2016-02-01 12:14:25
【问题描述】:

iam 在 postgresql 中使用以下命令创建表。

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

然后我执行 2 个插入语句。

  1. insert into someTable (col1,col2) values(1,11),(1,12);

    它的工作原理

  2. 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 on x86_64-pc-linux-gnu 编译,由 gcc ( Ubuntu 4.8.2-19ubuntu1) 4.8.2,64 位

但我有错误

执行两条语句后,我不需要这样放。

(1,11),(1,12),(1,13),(1,14)

【问题讨论】:

  • 第二个插入尝试插入值(1,11),您已经在第一个语句中插入了这些值。由于您已将 col1, col2 定义为唯一的,因此您不能将同一个元组插入两次。
  • 是否可以插入所有其他值(避免重复对)。?
  • 不能用 Postgres 9.1,你可以用 Postgres 9.5 做到这一点
  • 请参阅此处:stackoverflow.com/q/1009584/330315 和此处:stackoverflow.com/q/1109061/330315,了解旧 Postgres 版本的可能解决方案。请注意,9.1 将在 8 个月后停止支持,因此您无论如何都应该计划升级

标签: sql sql-insert postgresql-9.3


【解决方案1】:

您可以使用insert . . . select

insert into someTable(col1, col2) 
    select col1, col2
    from (select 1 as col1, 13 as col2 union all
          select 1, 14 union all
          select 1, 11
         ) t
    where not exists (select 1
                      from someTable st
                      where st.col1 = t.col1 and st.col2 = t.col2
                     );

即过滤掉insert之前的值。

编辑:

正如一匹无名马指出的那样,您也可以这样写:

insert into someTable(col1, col2) 
    select col1, col2
    from (values (1, 13), (1, 14), (1, 11)
         ) as t(col1, col2)
    where not exists (select 1
                      from someTable st
                      where st.col1 = t.col1 and st.col2 = t.col2
                     );

我倾向于使用union all 方法,因为并非所有数据库都支持values() 语句的这种用法。

【讨论】:

  • 派生表中不需要冗长的select。你可以直接在那里使用values (1,13), (1,14)
  • 我从上面的语法中得到了错误 ERROR: syntax error at or near "from" LINE 2: from (values (1, 13), (1, 14), (1, 11)
  • @AbdulManaf 。 . .不知何故,selectfrom 之前丢失了。
【解决方案2】:

使用 postgresql 9.5(最新版本)

像这样使用查询

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

无需任何额外代码即可避免重复。

【讨论】:

    猜你喜欢
    • 2011-10-30
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多