MySQL 不处理 ENUM 类型错误

标签 mysql sql mysql-5.5

我有这个脚本:

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_TABLESENUM 字段不应该获取第一个值而不是保留字段 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/

相关文章:

mysql - 连接两个表,结果显示在表 2 的 min() 字段上

mysql - 为什么在 "JOIN (SELECT)"语句中使用别名会导致错误?

mysql - 关于重复 key 更新 - 需要帮助

sql - Oracle SQL 根据列值将连续数字分配给一个子集

mysql - 根据多列查找匹配行(列的顺序无关紧要)

mysql - 是否可以检查特定查询在 MySQL 中打开了多少文件?

php - MySQL:忽略行之间差异大于 x 的结果

mysql - 在 CodeIgniter 中将 MySQL 查询转换为 Active Record

php - 带有 "WHERE"问题的小型 php fetch 查询

java - 如何将大文本存储到数据库中以将其称为网络博客文章(MySql)