Add unique constraint based on field value

后端 未结 1 599
日久生厌
日久生厌 2021-01-23 23:20

For the following table:

\"enter

I\'d like to add a constraint that if IsBanned fl

相关标签:
1条回答
  • 2021-01-23 23:48

    Actually, you can not define conditional structures in DDL syntax. Your field can be either NULL or NOT NULL - there's no third option (and it cannot depend of another field in structure)

    But you can still emulate desired behavior via triggers. You can interrupt UPDATE/INSERT statement if incoming data is invalid in terms of your logic. That can be done via:

    CREATE TRIGGER `bannedOnCheck`
    BEFORE INSERT ON `fa_ranking_system`.`Player`
    FOR EACH ROW
    BEGIN
      IF(new.IsBanned && new.BannedOn IS NULL) THEN
        SIGNAL 'Integrity check failed: can not set banned without ban date'
      END IF
    END
    
    0 讨论(0)
提交回复
热议问题