Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a MySQL table defined:

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 customerId we'd have only one primaryImage = 1.

So what else can I do to enforce this constraint?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
640 views
Welcome To Ask or Share your Answers For Others

1 Answer

MySQL perfectly supports unique constraints.

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)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...