How to enforce unique constraint in MySQL?

前端 未结 1 849
旧时难觅i
旧时难觅i 2020-12-09 16:01

I have a MySQL table defined:

File
--------------------------
ID int(11) PK
name varchar(100)
customerId int(11) FK
i         


        
相关标签:
1条回答
  • 2020-12-09 16:31

    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.

    0 讨论(0)
提交回复
热议问题