我有这个脚本:
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='STRICT_ALL_TABLES';
SET SQL_MODE = `STRICT_ALL_TABLES`;
CREATE TABLE IF NOT EXISTS `w_bank_account` (
`account_id` INT NOT NULL AUTO_INCREMENT,
`bank_id` INT(11) NOT NULL,
`account_number` VARCHAR(20) NOT NULL,
`account_type` ENUM('1','2') NOT NULL,
`balance` DECIMAL(19,4) NOT NULL DEFAULT 0,
`created` TIMESTAMP NOT NULL,
`modified` TIMESTAMP NULL,
PRIMARY KEY (`account_id`),
CONSTRAINT `fk_w_bank_account_n_bank1`
FOREIGN KEY (`bank_id`)
REFERENCES `n_bank` (`id`)
ON DELETE RESTRICT
ON UPDATE CASCADE)
ENGINE = InnoDB;
CREATE INDEX `fk_w_bank_account_n_bank1_idx` ON `w_bank_account` (`bank_id` ASC);
我尝试这两个查询:
INSERT INTO `w_bank_account` (`bank_id`, `account_number`, `account_type`, `balance`) VALUES
(1, '01234567890123456789', '1', 0.0000),
(1, '01234567890123456789', '6', 0.0000);
它可以工作,但在第二次插入时,它使 account_type
为空(我认为这会变为 NULL):-O 为什么如果我将 SQL_MODE
设置为 STRICT_ALL_TABLES? ENUM
字段不应该获取第一个值而不是保留字段 NULL
吗?我在 Debian 上使用 MySQL 5.5.31
最佳答案
http://dev.mysql.com/doc/refman/5.0/en/enum.html
If you insert an invalid value into an ENUM (that is, a string not present in the list of permitted values), the empty string is inserted instead as a special error value. This string can be distinguished from a “normal” empty string by the fact that this string has the numeric value 0. More about this later.
您可以使用此触发功能
delimiter //
CREATE TRIGGER upd_check BEFORE UPDATE ON `w_bank_account`
FOR EACH ROW
BEGIN
IF (NEW.`account_type` != '2' AND NEW.`account_type` != '1')
SET NEW.`account_type` = '1';
END IF;
END;//
delimiter ;
关于MySQL 不处理 ENUM 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18085419/