使用自动增量索引时避免插入重复项

时间:2020-09-30 20:20:39

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

我有一个查询:

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),但这并没有真正的帮助,因为我需要一次检查两个值。

1 个答案:

答案 0 :(得分:1)

on冲突子句在您要唯一的一组列上需要一个唯一约束或索引-好像您没有适当的约束或索引。

您可以在创建表格表格时对其进行设置:

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,用于演示使用和不使用唯一索引的行为。

相关问题