NOT NULL检查无效

时间:2016-04-29 03:35:51

标签: mysql constraints

我正在创建如下表格。

create table modifications (
    id bigint(20) AUTO_INCREMENT not null primary key,
    type varchar(100),
    user_id bigint(20) null,
    vulnerability_id bigint(20) null
)
alter table modifications
    add constraint fk_user_id foreign key (user_id) references app_user(id)
alter table modifications
    add constraint fk_vulnerability_id foreign key (vulnerability_id) references vulnerabilities(id)
alter table modifications
    add constraint ck_OneIsNotNull check (user_id is not null or vulnerability_id is not null)
alter table modifications
    add constraint ck_OneIsNull check (user_id is null or vulnerability_id is null)

我的目标是其中一列应为null,另一列不应为null。但是当我插入null或非null时,它接受而不会抛出错误。这是我使用的插入查询。

insert into modifications (type,user_id,vulnerability_id) values('vulnerability',16,65)
insert into modifications (type) values('vulnerability')

我哪里出错?

1 个答案:

答案 0 :(得分:2)

MySQL不强制执行CHECK约束。

MySQL Reference Manual中记录了这一点。

您可以创建BEFORE INSERT和BEFORE UPDATE触发器来强制执行此类约束。

例如:

 DELIMITER $$

 CREATE TRIGGER modifications_bi
 BEFORE INSERT ON modifications
 FOR EACH ROW
 BEGIN
    IF ( NEW.user_id IS NULL AND NEW.vulnerability_id IS NULL )
    OR ( NEW.user_id IS NOT NULL AND NEW.vulnerability_id IS NOT NULL ) THEN
      SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'Error: one must be null and one must be non-null';
    END IF;
END$$

DELIMITER ;

如果您运行的是5.5之前的版本,则不支持SIGNAL语法。要抛出异常,您需要运行导致异常的SQL语句。