在 PostgreSQL 中声明一个类型为 'not-null-string' 数组的列 [英] Declare a column of type 'not-null-string' array in PostgreSQL

查看:40
本文介绍了在 PostgreSQL 中声明一个类型为 'not-null-string' 数组的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 PostgreSQL 9.6 我可以创建一个类型为not-null-array of string"的列:

Using PostgreSQL 9.6 I can create a column with type 'not-null-array of string' with:

CREATE TABLE example (
    foo TEXT[] NOT NULL
);

但这允许元素为空,即我可以这样做:

but this allows the elements to be null, i.e I can do:

INSERT INTO example VALUES('{NULL}') 

有没有办法创建一个类型为not-null-array of not-null-string"的列?我想要这样的东西:

Is there a way to instead create a column with type 'not-null-array of not-null-string'? I'd like something like this:

CREATE TABLE example (
    foo (NOT NULL TEXT)[] NOT NULL
);

但它在语法上无效.有没有一种有效的方式来表达这一点?

but it's not syntactically valid. Is there a valid way to express this?

推荐答案

自 pg 9.5 起更简单,添加了 array_position()

Simpler since pg 9.5, with the addition of array_position()

CREATE TABLE example (
    foo TEXT[] NOT NULL check (array_position(foo, null) is null)
);

您可能还想检查空数组:

You might also want to check for an empty array:

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

这篇关于在 PostgreSQL 中声明一个类型为 'not-null-string' 数组的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆