mysql程序中的非空,MySQL中的非空约束

What's the best way to create a non-NULL constraint in MySQL such that fieldA and fieldB can't both be NULL. I don't care if either one is NULL by itself, just as long as the other field has a non-NULL value. And if they both have non-NULL values, then it's even better.

解决方案

MySQL 5.5 introduced SIGNAL, so we don't need the extra column in Bill Karwin's answer any more. Bill pointed out you also need a trigger for update so I've included that too.

CREATE TABLE foo (

FieldA INT,

FieldB INT

);

DELIMITER //

CREATE TRIGGER InsertFieldABNotNull BEFORE INSERT ON foo

FOR EACH ROW BEGIN

IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN

SIGNAL SQLSTATE '45000'

SET MESSAGE_TEXT = '\'FieldA\' and \'FieldB\' cannot both be null';

END IF;

END//

CREATE TRIGGER UpdateFieldABNotNull BEFORE UPDATE ON foo

FOR EACH ROW BEGIN

IF (NEW.FieldA IS NULL AND NEW.FieldB IS NULL) THEN

SIGNAL SQLSTATE '45000'

SET MESSAGE_TEXT = '\'FieldA\' and \'FieldB\' cannot both be null';

END IF;

END//

DELIMITER ;

INSERT INTO foo (FieldA, FieldB) VALUES (NULL, 10); -- OK

INSERT INTO foo (FieldA, FieldB) VALUES (10, NULL); -- OK

INSERT INTO foo (FieldA, FieldB) VALUES (NULL, NULL); -- gives error

UPDATE foo SET FieldA = NULL; -- gives error

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值