Mysql unique constraint allowing single row for a combination

前端 未结 5 1352
囚心锁ツ
囚心锁ツ 2021-01-20 01:25

Is it possible to have a unique constraint such that one particular column has a value only once?

For instance

-----------------------    
name | pri         


        
5条回答
  •  野性不改
    2021-01-20 02:09

    Here is a workaround which might suit your needs. Consider the following table definition and unique constraint:

    CREATE TABLE prices
    (
        id int NOT NULL AUTO_INCREMENT,
        name varchar(255) NOT NULL,
        price int,
        default varchar(255)
    )
    
    ALTER TABLE prices ADD UNIQUE idx (id, name, default);
    

    In your app layer, when you INSERT records when default is FALSE, always leave the id column NULL. This will cause MySQL to always add a unique value for the id, so that duplicate values for name and default may be entered (i.e. a default value of FALSE may occur multiple times for a given name).

    However, when you INSERT a record with default being TRUE, you should always use the same id value. This will ensure that a given name can only appear once as TRUE.

提交回复
热议问题