Mysql Constraint Check Workarounds(MYSQL不支持约束的处理)


Mysql Constraint Check Workarounds MYSQL不支持约束的处理

http://forums.mysql.com/read.php?136,152474,240479#msg-240479


As the MySQL Reference Manual says:
"The CHECK clause is parsed but ignored by all storage engines."
MySQL does not support CHECK constraints.
It’s a bug of MySQL. (http://bugs.mysql.com/bug.php?id=25660 )

 

The way I do a constraint check is with TRIGGER (see : http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html ).
You can use a trigger to route the update to an error condition like duplicate key.


Basically, for your table, you would say:

DELIMITER $$
CREATE TRIGGER trig_gvars_gfirst BEFORE UPDATE ON gvars
FOR EACH ROW BEGIN
IF NEW.name NOT LIKE 'g%' THEN
SET NEW.name = 1 / 0;
END IF;
END $$

DELIMITER ;


Basically, the line "SET NEW.name = 1 / 0;" will occur and force an error any time the constraint is not satisfied. That seems to be the best way to cause the insertions not to happen. Quite dirty -- but it beats just getting ignored by the database engine. This also doesn't work if you're updating through FOREIGN KEY actions, such as CASCADE or UPDATE, as TRIGGERs are not called for these actions. So watch out for that.

Another solution would be to restrict insertion of data into tables you would like to constrain through user-defined functions and procedures. This requires enumerating every possible action scheme you might want to take, so it is generally not the best option.

 

 

不能使用ENUM 类型来代替Constraint Check, MySQL 认为 ENUM 类型集合中出现的值是合法输入,除此之外其它任何输入都将会使 MySQL 在这个字段中插入一个空字符串, 而不是插入失败.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值