如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 20:27:41  来源:igfitidea点击:

How to enforce unique constraint in MySQL?

mysqlsqldatabasedatabase-design

提问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 CONSTRAINTwith a WHEREcondition. For each customerIdwe'd have only one primaryImage = 1.


我在这里读到 MySQL 不支持UNIQUE CONSTRAINTWHERE条件的a 。对于每个customerId,我们只有一个primaryImage = 1

So what else can I do to enforce this constraint?

那么我还能做些什么来强制执行这个约束呢?

回答by Quassnoi

MySQLperfectly supports unique constraints.

MySQL完美支持唯一约束。

It does not support partial constraints/indexes, though, so you would need to mark non-primary images with a NULLinstead of 0.

它不支持部分限制/索引,虽然,所以你需要用标记非主图像NULL代替0

ALTER TABLE file ADD CONSTRAINT ux_file_customer_primary 
UNIQUE (customerId, isPrimaryImage)

You can insert arbitrary number of NULLvalues into isPrimaryImagebut only one non-null value per customer.

您可以NULLisPrimaryImage每个客户插入任意数量的值,但只能插入一个非空值。