Add unique constraint based on field value

删除回忆录丶 提交于 2019-12-31 04:08:27

问题


For the following table:

I'd like to add a constraint that if IsBanned flag is set to true, the BannedOn field cannot be left empty (cannot be set to null).

How can I do this in MySQL? Here's my CREATE syntax:

CREATE TABLE IF NOT EXISTS `fa_ranking_system`.`Player` (
  `PlayerID` INT NOT NULL AUTO_INCREMENT,
  `FK_ServerID` INT NOT NULL,
  `PlayerName` VARCHAR(15) NOT NULL,
  `RegDate` DATETIME NOT NULL,
  `IsBanned` TINYINT(1) NOT NULL,
  `LastUpdatedOn` DATETIME NOT NULL,
  `LastUpdatedBy` VARCHAR(20) NOT NULL,
  `BannedOn` DATETIME NULL,
  PRIMARY KEY (`PlayerID`, `FK_ServerID`),
  INDEX `fk_Player_Server_idx` (`FK_ServerID` ASC),
  CONSTRAINT `fk_Player_Server`
    FOREIGN KEY (`FK_ServerID`)
    REFERENCES `fa_ranking_system`.`Server` (`ServerID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)

回答1:


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


来源:https://stackoverflow.com/questions/18459937/add-unique-constraint-based-on-field-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!