MySQL basis (6) | check constraints

MySQL basis (6) | check constraints


Foreword

In some cases, we need to enter the field in a specified range,
for example: gender only enter 'M' or 'female', only the balance is greater than 0 and other conditions,
we in addition to the control program, we can use CHECK constraints to standardize data.

"" "However:
MySQL storage engines do not support all of the check constraint, MySQL will check clause analysis, but when you insert data will be ignored, so check does not work, so there are two ways to achieve data constraints:
1. mysql bound species, such as using enum type flip-flop or the like.
2. The data used in the application which then inserted.

method one

Use ENUM limit value inserted, but this approach can only be used for discrete data, range data for the powerless

-- 创建一张测试表,规定sex字段只能是 ‘男’ 或者 ‘女’
CREATE TABLE `user` (
  `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(18) COLLATE utf8_estonian_ci NOT NULL,
  `sex` ENUM('男','女') COLLATE utf8_estonian_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_estonian_ci

测试:
INSERT INTO `user`(`name`,`sex`) VALUES('秀吉','秀吉');

结果:
错误代码: 1265
Data truncated for column 'sex' at row 1

Method Two

If we need to restrict the range of data, for example: only the balance is greater than 100 such conditions, we can use triggers to implement.

DELIMITER $$
CREATE
    TRIGGER `remaining_BeforeInsert` BEFORE INSERT ON `user`
    FOR EACH ROW BEGIN
    IF NEW.remaining > 100 THEN  
        SET NEW.remaining = 100;  
    END IF;  
    END$$
DELIMITER ;

Reference: https://www.cnblogs.com/lixingwu/p/7280597.html

Guess you like

Origin www.cnblogs.com/iwsx/p/12348975.html