我是靠谱客的博主 激动月光,最近开发中收集的这篇文章主要介绍mysql 常量_MySQL表中的常量列值,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

bd96500e110b49cbb3cd949968f18be7.png

I have a table in MySQL. I'd like to set a column value for a table to be a constant integer. How can I do this?

解决方案Unfortunately MySQL does not support SQL check constraints. You can

define them in your DDL query for compatibility reasons but they are

just ignored. You can create BEFORE INSERT and BEFORE UPDATE triggers

which either cause an error or set the field to its default value when

the requirements of the data are not met.

So here you can find a way around through MYSQL TRIGGER.

Sample Table:

DROP TABLE IF EXISTS `constantvaluetable`;

CREATE TABLE `constantvaluetable` (

`ID` int(11) NOT NULL AUTO_INCREMENT,

`constValue` int(11) NOT NULL,

PRIMARY KEY (`ID`)

) ENGINE=InnoDB;

Trigger:

DROP TRIGGER IF EXISTS trigger_const_check;

delimiter //

CREATE TRIGGER trigger_const_check BEFORE INSERT ON constantvaluetable

FOR EACH ROW

BEGIN

IF NEW.constValue <> 71 THEN

SIGNAL SQLSTATE '45000' SET message_text ='Only allowed value is 71';

END IF;

END //

delimiter ;

Test:

INSERT INTO constantvaluetable(constValue) VALUES(71);

INSERT INTO constantvaluetable(constValue) VALUES(66);

Result:

The first insert statement will succeed.

The second insert statement will fail. And the following error message will be shown:

[Err] 1644 - Only allowed value is 71

Note: Assuming your CONSTANT value is 71.

最后

以上就是激动月光为你收集整理的mysql 常量_MySQL表中的常量列值的全部内容,希望文章能够帮你解决mysql 常量_MySQL表中的常量列值所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部