我有一个非常简单的表格
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/