sql—如何声明数组的元素不可为空?

zaqlnxep  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(438)

在下面的简单表格中

CREATE TABLE foo (
  things VARCHAR ARRAY
);

可以插入 null 作为 things :

INSERT INTO foo VALUES ('{"hi", null, "ho"}');

但我不允许这样。
但是,将定义改为:,

CREATE TABLE foo (
  things VARCHAR ARRAY NOT NULL
);

只会防止这种情况

INSERT INTO foo VALUES (null);

这不是我想要的(我还是想允许的。)
那么,如何才能不声明列,而声明数组列的元素不可为null呢?

8aqjt8rx

8aqjt8rx1#

可以使用检查约束:

CREATE TABLE foo 
(
  things text[], 
  constraint check_things_not_null 
    check ( cardinality(things) = cardinality(array_remove(things, null)))
);

或者你可以使用 array_position() ```
CREATE TABLE foo
(
things text[],
constraint check_things_not_null
check ( array_position(things, null) is null)
);

sd2nnvve

sd2nnvve2#

你可以用 checkarray_position() 如下所示

CREATE TABLE foo (
  things text[] NOT NULL check (array_position(things, null) is null)
);

还可以检查空数组

CREATE TABLE foo (
  things text[] NOT NULL check (things <> '{}' and array_position(things, null) is null)
);

相关问题