是否可以在通用数据库中指定数据值的范围?

Is it possible to specify the range of data values in general database?

我想在通用数据库中处理一定范围内的一些数据,并预定义每个数据项的范围。一些的范围是连续的,比如从最小值到最大值的浮点数,而另一些的范围是离散的,比如人的国籍可能是美国、日本或西班牙,一个很大但有限的范围备择方案。这种模式通常在业务逻辑层实现,我想知道我是否也可以在数据库层处理它,尤其是在非SQL数据库中。

在我写这个答案的时候,这个问题是针对一般数据库的,而不是特定于非SQL数据库的。

在许多(关系)数据库中,您可以使用数据库中的 check 约束来处理此问题,该数据库允许您使用布尔表达式定义 acceptable 值。这将适用于插入和更新语句。

适用于 MSSQL 和 Postgresql 的示例:

create table t 
(
    -- country_code has to be a Nordic country.
    country_code varchar(20) check (country_code in ('NO','SE','DK', 'FI','IS')),

    -- float_value has to be in a certain range
    float_value float check (float_value between 0.01 and 0.05),

    -- int_value has to be in a range, and in steps of 5
    int_value int check ( (int_value between 10 and 50) and (int_value % 5 = 0) )
);

-- allowed
insert into t values ('SE', 0.03, 25);
-- not allowed as int_value is not divisible by 5
insert into t values ('SE', 0.03, 26);
-- disallowed due to country_code not in set
insert into t values ('US', 0.05, 25);

有关更多信息和示例,请参阅 documentation for Postgresql

另一种选择是在插入之前使用触发器或代替插入,这使您可以验证数据并执行比检查约束允许的更复杂的处理(如其他 table 中的参考数据)。不过,触发器可能对性能不利。

如果您想将可能值的范围限制在预定义的范围内,您还可以将这些值存储在 table 中(如 countries(code, name))并使用 foreign key 约束来确保无法插入相关域 table.

中不存在的数据