sql - 当一列可以为空时,如何在 2 列上设置唯一约束

标签 sql ruby-on-rails postgresql activerecord

我有一个非常简单的表格

categories(parent_id, title)

我正在尝试设置唯一约束,以便两个类别不能具有相同的标题和父级。

class CreateCategories < ActiveRecord::Migration
  def change
    create_table :categories do |t|
      t.integer :parent_id
      t.string  :title, :null => false
    end
    add_index :categories, [:title, :parent_id], :unique => true   
  end
end

当 parent_id 为 null 时,它不会强制标题的唯一性,而这正是我们所需要的。是否可以确保标题对于根类别也是唯一的?

最佳答案

您可以为此创建一个唯一索引:

CREATE UNIQUE INDEX ix_categories_root_title
    ON categories (title)
    WHERE parent_id IS NULL

与依赖触发器或应用程序级验证相比,您晚上会睡得更好 :P

关于sql - 当一列可以为空时,如何在 2 列上设置唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6970933/

相关文章:

用于 Xpath 查询的 SQL Xml

ruby-on-rails - 使用 rake 数据库 :migrate inside another task leaves pending migrations

ruby-on-rails - 为什么 .with_lock 没有按我的预期工作?

ruby-on-rails - Rails 3 未登录开发

java - 如何转换为 PostgreSQL 数字类型?

postgresql - POSTGRES datetime2 到时间戳

postgresql - 如何通过 Kotlin Exposed ORM 使用 Postgresql 枚举类型?

sql - 从多个 TableView PostgreSQL 中获取游标

sql - 在 SAS SQL 中使用宏

mysql - 添加基于字段值的唯一约束