【问题标题】:Avoid inserting duplicates when using autoincrementing index使用自动递增索引时避免插入重复项
【发布时间】:2020-09-30 20:20:39
【问题描述】:

我有一个问题:

INSERT INTO tweet_hashtags(hashtag_id, tweet_id)
VALUES(1, 1) 
ON CONFLICT DO NOTHING 
RETURNING id

它工作正常并使用id = 1 插入,但是当有重复时,假设另一个(1, 1) 它使用id = 2 插入。我想防止这种情况发生,我读到我可以做到ON CONFLICT (col_name),但这并没有真正帮助,因为我需要一次检查两个值。

【问题讨论】:

    标签: sql postgresql sql-insert unique-constraint unique-index


    【解决方案1】:

    on conflict 子句要求在您希望唯一的列集上具有唯一约束或索引 - 而您似乎没有这样做。

    你可以在创建表的时候设置:

    create table tweet_hashtags(
        id serial primary key, 
        hashtag_id int, 
        tweet_id int, 
        unique (hashtag_id, tweet_id)
    );
    

    或者,如果表已经存在,你可以创建一个唯一索引(但你需要先去掉重复的):

    create unique index idx_tweet_hashtags on tweet_hashtags(hashtag_id, tweet_id);
    

    那么您的查询应该可以正常工作:

    insert into tweet_hashtags(hashtag_id, tweet_id)
    values(1, 1) 
    on conflict (hashtag_id, tweet_id) do nothing 
    returning id
    

    指定冲突目标可以使意图更清晰,通常应该是首选(尽管do nothing 不是强制性的)。

    请注意,跳过插入时查询不返回任何内容(即不返回现有的id)。

    这是一个demo on DB Fiddle,它演示了使用和不使用唯一索引时的行为。

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 2020-06-18
      • 2015-06-13
      相关资源
      最近更新 更多