我想将表格行中的字段值限制为特定范围.是否可以将我的relationship_level字段限制为[0.00到1.00]?
目前我正在使用DECIMAL(2,2),它不允许DECIMAL(1,2),因为M必须是> = D.我假设数据类型DECIMAL(2,2)实际上将允许来自00.00到99.99?
CREATE TABLE relationships (
from_user_id MEDIUMINT UNSIGNED NOT NULL,
to_user_id MEDIUMINT UNSIGNED NOT NULL,
relationship_level DECIMAL(2,2) UNSIGNED NOT NULL,
PRIMARY KEY (from_user_id, to_user_id),
FOREIGN KEY (from_user_id) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE NO ACTION,
FOREIGN KEY (to_user_id) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE NO ACTION,
INDEX relationship_from_to (to_user_id, from_user_id, relationship_level)
) ENGINE = INNODB;
有没有更好的方法来做到这一点,谁能预见到任何限制?
非常感谢!
解决方法:
您可以使用触发器在MySQL中模拟检查约束.
例如,如果要强制将大于1.00的所有值存储为1.00,则可以使用以下两个触发器执行此操作:
DELIMITER $$
DROP TRIGGER IF EXISTS tr_b_ins_relationships $$
CREATE TRIGGER tr_b_ins_relationships BEFORE INSERT ON relationships FOR EACH ROW BEGIN
IF new.relationship_level > 1
THEN
SET new.relationship_level = 1;
END IF;
END $$
DELIMITER ;
DELIMITER $$
DROP TRIGGER IF EXISTS tr_b_upd_relationships $$
CREATE TRIGGER tr_b_upd_relationships BEFORE UPDATE ON relationships FOR EACH ROW BEGIN
IF new.relationship_level > 1
THEN
SET new.relationship_level = 1;
END IF;
END $$
DELIMITER ;
标签:mysql,decimal,database-schema,sqldatatypes
来源: https://codeday.me/bug/20190521/1146366.html