gpt4 book ai didi

mysql - 如何在 MySQL 中强制执行唯一约束?

转载 作者:IT老高 更新时间:2023-10-28 23:45:52 26 4
gpt4 key购买 nike

我定义了一个 MySQL 表:

File
--------------------------
ID int(11) PK
name varchar(100)
customerId int(11) FK
isPrimaryImage tinyint(1)
....


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

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

最佳答案

MySQL 完美支持唯一约束。

不过,它不支持部分约束/索引,因此您需要使用 NULL 而不是 0 来标记非主图像。

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

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

关于mysql - 如何在 MySQL 中强制执行唯一约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6679122/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com