MySQL插入选择不执行NOT NULL约束

时间:2016-12-23 00:10:52

标签: mysql foreign-keys constraints notnull insert-select

在运行INSERT INTO xxx (col) SELECT ...时,我遇到了MySQL 5.6 InnoDb忽略NOT NULL外键的问题。在以其他格式运行insert语句时,可以正确实施约束。启用了外键检查,sql_mode = STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ENGINE_SUBSTITUTION

以下是一个例子:

CREATE TABLE Test_Parent
(
    id BIGINT(18) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    dummy VARCHAR(255)
) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_unicode_ci
    COMMENT 'Test parent table';

CREATE TABLE Test_Child
(
    id BIGINT(18) unsigned PRIMARY KEY NOT NULL AUTO_INCREMENT,
    fid BIGINT UNSIGNED NOT NULL,
    FOREIGN KEY Fk_Test_Parent_01(fid) REFERENCES Test_Parent(id)
) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_unicode_ci
    COMMENT 'Test child table';

INSERT INTO Test_Parent(dummy)
VALUES ('test');

## Here's where the FK constraint should be enforced but isn't ##
INSERT INTO Test_Child(fid)
SELECT id
    FROM Test_Parent
WHERE dummy = 'missing value';

1 row affected in 5ms

## Running an insert with a different format, the constraint is enforced ##
INSERT INTO Test_Child(fid)
VALUES (null);
Column 'fid' cannot be null

## Running this format, the foreign key is also enforced ##
INSERT INTO Test_Child(id, fid)
VALUES (123, (SELECT id FROM Test_Parent WHERE dummy = 'missing value'));
Column 'fid' cannot be null

我不明白为什么MySQL会为3个插入语句中的2个强制执行外键。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

来自您客户的误导性1 row affected in 5ms消息可能会引起混淆。在您提到的评论主题中,IntelliJ报告了该消息,但我在MySQL 5.6.35和5.7.16-ubuntu中都运行了定义良好的测试表,在这两个版本中,有问题的语句报告了0个受影响的行:

mysql > INSERT INTO Test_Child(fid)
    -> SELECT id
    ->     FROM Test_Parent
    -> WHERE dummy = 'missing value';
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

因此,查看误导性受影响的行消息,这里真正发生的是SELECT语句的INSERT...SELECT部分不匹配任何行,因此MySQL不会尝试插入任何行。因此没有外键约束违规。

INSERT INTO...SELECT的格式与后面的示例略有不同:

INSERT INTO Test_Child(id, fid)
VALUES (123, (SELECT id FROM Test_Parent WHERE dummy = 'missing value'));

...因为在这种情况下,数字文字123强制插入一行,并且它与从子选择返回的null值配对。因此尝试插入null并导致约束违规。

如果强制INSERT...SELECT返回一个空值的行,则可能因违反约束而失败:

INSERT INTO Test_Child (fid)
-- Return a literal NULL row...
SELECT NULL as id FROM Test_Parent
-- Column fid cannot be null