外键列的默认值 - InnoDB

时间:2014-09-20 16:38:15

标签: mysql innodb default-value

采取以下SQL小提琴:

  

http://sqlfiddle.com/#!2/ae0df/1

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';


CREATE TABLE IF NOT EXISTS `vatbands` (
  `vatbands_id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `code` ENUM('A', 'B', 'C', 'D', 'E', 'F') NOT NULL,
  `client_id` INT(11) UNSIGNED NOT NULL,
  PRIMARY KEY (`vatbands_id`, `code`, `client_id`),
  INDEX `vatcode_vatbands` (`code` ASC, `client_id` ASC))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS `item` (
  `item_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `client_id` INT(11) UNSIGNED NOT NULL COMMENT 'Customer ID',
  `vatcode` ENUM('A', 'B', 'C', 'D', 'E', 'F') DEFAULT 'A',
  PRIMARY KEY (`item_id`, `client_id`),
  INDEX `vatcode_item` (`vatcode` ASC, `client_id` ASC),
  CONSTRAINT `vatcode_item`
    FOREIGN KEY (`vatcode` , `client_id`)
    REFERENCES `sbs_node`.`vatbands` (`code` , `client_id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

START TRANSACTION;
INSERT INTO `vatbands` (`client_id`, `code`) VALUES ('1', 'A');
INSERT INTO `item` (`client_id`, `vatcode`) VALUES ('1', NULL);
COMMIT;

当指定默认值“A”时,为什么vatcode列为'空'?

1 个答案:

答案 0 :(得分:1)

documentation of the ENUM type州:

  

如果声明ENUM列允许NULL,则NULL值为a   列的有效值,默认值为NULL。如果是ENUM   列声明为NOT NULL,其默认值是第一个元素   允许值列表。

您的INSERT正在使用NULL值:

INSERT INTO `item` (`client_id`, `vatcode`) VALUES ('1', NULL);

将您的CREATE TABLE声明更改为

CREATE TABLE IF NOT EXISTS `item` (
  `item_id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `client_id` INT(11) UNSIGNED NOT NULL COMMENT 'Customer ID',
  `vatcode` ENUM('A', 'B', 'C', 'D', 'E', 'F') NOT NULL,        -- no default, but NOT NULL           
  PRIMARY KEY (`item_id`, `client_id`),
  INDEX `vatcode_item` (`vatcode` ASC, `client_id` ASC),
  CONSTRAINT `vatcode_item`
    FOREIGN KEY (`vatcode` , `client_id`)
    REFERENCES `vatbands` (`code` , `client_id`)     -- corrected that one too
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

和您的INSERT语句:

INSERT INTO `item` (`client_id`, `vatcode`) VALUES ('1', DEFAULT);

要获得所需的结果,请参阅my updated fiddle