限制检查约束中的总行数

Constrain total number of rows in check constraint

我想创建一个 table 一次只能包含固定数量的行,例如只有一个:

create table test (
    someId INT not null,
    comment VARCHAR(4096) null,
    check((select count(*) from test) < 2)
)

但是不允许给定的检查约束:

Error: Aggregates or subqueries are not allowed in check constraints.

SQLState: ZZZZZ ErrorCode: 7356

是否有替代方法?

您似乎想要创建一个 table 保证最多只有一行。这似乎是 table 的不寻常用法。通常,我会推荐一个触发器。

因为你只想要一行,你可以使用这个技巧:

create table test (
    someId INT not null,
    comment VARCHAR(4096) null,
    guarantee_one_row int default 0,
    constraint test_only_one_row unique(guarantee_one_row)
);

它添加一个具有默认值的列,然后在其上定义唯一约束。

我应该指出,您也可以使用计算列执行此操作:

create table test (
    someId INT not null,
    comment VARCHAR(4096) null,
    guarantee_one_row as ('one row') materialized,
    constraint test_only_one_row unique(guarantee_one_row)
);