【问题标题】:postgres create unique row in tablepostgres 在表中创建唯一行
【发布时间】:2021-10-19 04:13:43
【问题描述】:

我使用 Postgres。

我有一个这样的表,我知道我无法创建具有超过 1 个空列的唯一索引。

如何创建表格,以便如果我像这样插入 2 次 obj 它将归档:

{
  content_details_id: 1,
  topic_id: 1,
  subject_id: null,
  chapter_id: null, 
  sub_chapter_id: null,
  learning_unit_id: null, 
  points: null 
}
    CREATE TABLE IF NOT EXISTS content_details_connections(
    id SERIAL PRIMARY KEY,
     content_details_id INT REFERENCES content_details(id) on update no action on delete cascade NOT 
     NULL,
     topic_id INT REFERENCES topics(id) on update no action on delete cascade,
     subject_id INT REFERENCES subjects(id) on update no action on delete cascade,
     chapter_id INT REFERENCES chapters(id) on update no action on delete cascade,
     sub_chapter_id INT REFERENCES sub_chapters(id) on update no action on delete cascade,
     learning_unit_id INT REFERENCES learning_unit(id) on update no action on delete cascade,
     points INT,
     created_at TIMESTAMP DEFAULT NOW()::TIMESTAMP,
     last_updated TIMESTAMP DEFAULT NOW()::TIMESTAMP,            
     UNIQUE(content_details_id,topic_id,subject_id,chapter_id,sub_chapter_id,learning_unit_id,points))

【问题讨论】:

  • 不相关,但:NOW()::TIMESTAMPlocaltimestamp 相同

标签: postgresql ddl


【解决方案1】:

使用唯一索引:

CREATE UNIQUE INDEX ON content_details_connections (
   content_details_id,
   coalesce(topic_id, -1),
   coalesce(subject_id, -1),
   coalesce(chapter_id, -1),
   coalesce(sub_chapter_id, -1),
   coalesce(learning_unit_id, -1),
   coalesce(points, -1)
);

这假定 -1 是表中没有出现的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 2016-02-15
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多