MySql唯一约束 [英] MySql Unique Constraint

查看:194
本文介绍了MySql唯一约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MySql表定义:

I have a MySql table defined:

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

我在这里读到MySql支持一个具有WHERE条件的UNIQUE CONSTRAINT ...对于每个customerId,我们只有一个primaryImage = 1.所以...我还能做什么来强制这个约束?

I've read here that MySql doesn't support a UNIQUE CONSTRAINT with a WHERE condition...for each customerId we'd have only one primaryImage = 1. So...What else can I do to enforce this constraint?

推荐答案

MySQL 完美支持唯一约束。

支持部分约束/索引,因此您需要使用 NULL 而不是 0

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

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

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

You can insert arbitrary number of NULL values into isPrimaryImage but only one non-null value per customer.

这篇关于MySql唯一约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆