Mysql unique constraint allowing single row for a combination

前端 未结 5 1225
囚心锁ツ
囚心锁ツ 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:04

    Putting a simple unique constraint over all three columns would not work because it would allow the following:

    name | price | default
    -----------------------
    XYZ  |  20   | TRUE
    XYZ  |  30   | TRUE
    XYZ  |  40   | FALSE
    ABC  |  50   | FALSE
    

    In other SQL engines, you could just create a check constraint that ensures that for every set of name rows, the number of those rows with default = TRUE is <= 1. However, MySQL does not support enforcing check constraints.

    In MySQL you could implement this via insert and update triggers instead:

    CREATE TRIGGER `before_insert` BEFORE INSERT ON `tableName`
    FOR EACH ROW
    BEGIN
    
       DECLARE @sum INT
    
       SELECT @sum = SUM(CASE WHEN [default] = TRUE THEN 1 ELSE 0 END)
       FROM tableName
       WHERE [name] = new.[name]
    
       IF (@sum = 0 OR new.default = FALSE)
       BEGIN
          INSERT INTO tableName (name, price, default)
          VALUES (new.[name], new.[price], new.[defaul]t)
    
       END
    END
    

    And similarly for the update.

提交回复
热议问题