如何在 MySQL 中强制执行唯一约束?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6679122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to enforce unique constraint in MySQL?
提问by kasdega
I have a MySQL table defined:
我定义了一个 MySQL 表:
File
--------------------------
ID int(11) PK
name varchar(100)
customerId int(11) FK
isPrimaryImage tinyint(1)
....
I've read here that MySQL doesn't support a UNIQUE CONSTRAINT
with a WHERE
condition. For each customerIdwe'd have only one primaryImage = 1.
我在这里读到 MySQL 不支持UNIQUE CONSTRAINT
带WHERE
条件的a 。对于每个customerId,我们只有一个primaryImage = 1。
So what else can I do to enforce this constraint?
那么我还能做些什么来强制执行这个约束呢?
回答by Quassnoi
MySQL
perfectly supports unique constraints.
MySQL
完美支持唯一约束。
It does not support partial constraints/indexes, though, so you would need to mark non-primary images with a NULL
instead of 0
.
它不支持部分限制/索引,虽然,所以你需要用标记非主图像NULL
代替0
。
ALTER TABLE file ADD CONSTRAINT ux_file_customer_primary
UNIQUE (customerId, isPrimaryImage)
You can insert arbitrary number of NULL
values into isPrimaryImage
but only one non-null value per customer.
您可以NULL
向isPrimaryImage
每个客户插入任意数量的值,但只能插入一个非空值。