如何避免在 mysql 中外键有两个空值?

How can I avoid in mysql that I have two null values on foreign keys?

我得到了一个 table user、一个 table assignment 和一个 table candidation(有一个单独的主,而不是natural one) 具有指向其他两个的外键。它们都是1:nc,意味着不能总是有一个用户进行候选(删除用户)或分配(删除作业)。

现在我怎样才能避免在两个外键中都有NULL

用户:

-- Table `Ressource-Management`.`user`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Ressource-Management`.`user` (
  `iduser` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '',
  `name_first` VARCHAR(50) NOT NULL COMMENT '',
  `name_last` VARCHAR(50) NOT NULL COMMENT '',
  `attendance` INT UNSIGNED NOT NULL COMMENT '',
  `can_own` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '',
  PRIMARY KEY (`iduser`)  COMMENT '')
ENGINE = InnoDB;

作业:

-- -----------------------------------------------------
-- Table `Ressource-Management`.`assignment`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Ressource-Management`.`assignment` (
  `idassignment` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '',
  `owner` INT UNSIGNED NOT NULL COMMENT '',
  `budget` INT UNSIGNED NOT NULL COMMENT '',
  `priority` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '',
  `date_to` DATETIME NULL COMMENT '',
  PRIMARY KEY (`idassignment`)  COMMENT '',
  INDEX `fk_assignment_user_idx` (`owner` ASC)  COMMENT '',
  CONSTRAINT `fk_assignment_user`
    FOREIGN KEY (`owner`)
    REFERENCES `Ressource-Management`.`user` (`iduser`)
    ON DELETE RESTRICT
    ON UPDATE CASCADE)
ENGINE = InnoDB;

候选人:

-- -----------------------------------------------------
-- Table `Ressource-Management`.`candidation`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Ressource-Management`.`candidation` (
  `idcandidation` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '',
  `user_iduser` INT UNSIGNED NULL COMMENT '',
  `assignment_idassignment` INT UNSIGNED NULL COMMENT '',
  `date_from` DATETIME NOT NULL COMMENT '',
  `date_to` DATETIME NOT NULL COMMENT '',
  `status` LONGBLOB NULL DEFAULT offen COMMENT '',
  `message` VARCHAR(4096) NULL COMMENT '',
  PRIMARY KEY (`idcandidation`)  COMMENT '',
  INDEX `fk_user_has_assignment_assignment1_idx` (`assignment_idassignment` ASC)  COMMENT '',
  INDEX `fk_user_has_assignment_user1_idx` (`user_iduser` ASC)  COMMENT '',
  UNIQUE INDEX `user_assignment_UNIQUE` (`user_iduser` ASC, `assignment_idassignment` ASC)  COMMENT '',
  CONSTRAINT `fk_user_has_assignment_user1`
    FOREIGN KEY (`user_iduser`)
    REFERENCES `Ressource-Management`.`user` (`iduser`)
    ON DELETE SET NULL
    ON UPDATE CASCADE,
  CONSTRAINT `fk_user_has_assignment_assignment1`
    FOREIGN KEY (`assignment_idassignment`)
    REFERENCES `Ressource-Management`.`assignment` (`idassignment`)
    ON DELETE SET NULL
    ON UPDATE CASCADE)
ENGINE = InnoDB;

如果导致空值的唯一原因是删除记录,请使用逻辑删除:向两个表添加标志 isDeleted 并将 candidation 中的外键字段设为 NOT NULL.

一种可能性是在删除时创建触发器,如果​​另一个键已经是 NULL

,我将放弃删除