mysql - 设置列的范围

标签 mysql sql

我在我的数据库中使用了一定范围的许多字段,例如:

CREATE TABLE figures (
    deg FLOAT,-- between 0 and pi
    prc FLOAT,-- between 0 and 1
    .......
);
CREATE TRIGGER filter1 BEFORE UPDATE ON figures FOR EACH ROW SET
    NEW.deg=IF(NEW.deg>3.1415926 OR NEW.deg<0, OLD.deg,NEW.deg),
    NEW.prc=IF(NEW.prc>1 OR NEW.prc<0, OLD.prc,NEW.prc),
    ..........;
CREATE TRIGGER filter2 BEFORE INSERT ON figures FOR EACH ROW SET
    NEW.deg=IF(NEW.deg>3.1415926 OR NEW.deg<0, NULL,NEW.deg),
    NEW.prc=IF(NEW.prc>1 OR NEW.prc<0, NULL,NEW.prc),
    .........;

有什么办法写得更清楚吗?
像这样的东西:

--CREATE PROCEDURE/FUNCTION between()..................
CREATE TABLE figures (
    deg FLOAT between(0,3.1415),
    prc FLOAT between(0,1),
    .......

至少,我不想将每个过滤器都写两次。 (插入时、更新时)

最佳答案

MySQL 8.0.16 之前的版本 触发器是最好的解决方案 回复:检查约束...

'The CHECK clause is parsed but ignored by all storage engines.'.....

'The reason for accepting but ignoring syntax clauses is for compatibility, to 
make it easier to port code from other SQL servers, and to run applications 
that create tables with references. '

直接来自:http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

从 MySQL 8.0.16 开始,它们现在可以按照您的预期工作

  CREATE TABLE figures (
    deg FLOAT, 
    prc FLOAT,   
    CONSTRAINT `deg_min` CHECK ((`deg` > 0)),
    CONSTRAINT `deg_max` CHECK ((`deg` < 3.1415)),
    CONSTRAINT `prc_min` CHECK ((`prc` > 0)),
    CONSTRAINT `prc_max` CHECK ((`prc` < 1))
  )

关于mysql - 设置列的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7709949/

相关文章:

php - PHP 中的希腊字符

php - PHPBB 标签中的这些字符是什么意思?

php - 可捕获的 fatal error : Object of class stdClass could not be converted to string

sql - Regexp_Replace Oracle 中具有相同替换次数的字符的多次出现

javascript - Oracle ApEx复选框可在选中/未选中时操纵其他值

MySQL对三个相互连接的表进行连接查询

mysql - PDO 更新 - 保持原始值

mysql - 在mysql中的四个表中找到最大值

mysql 选择最近 7 天的查询,如果一天中有更多查询,则只显示总和

mysql - SQL 查询中的 CONVERT 或 CAST 字段