sql - 如何声明数组的元素不可为空?
问题描述
在下面的简单表格中
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);
这不是我想要的。(我仍然想允许这样做。)
那么我怎样才能声明不是列,而是数组列的元素不可为空呢?
解决方案
您可以使用check
witharray_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)
);
推荐阅读
- python - 自定义列表输出
- c - 对 ev_timer_stop 的未定义引用
- android - 为什么我的 webView 不显示任何内容并自动将我重定向到内置浏览器?
- amazon-cloudformation - 云形成配置取决于正在创建的区域
- c# - 如何在 datagridview 中选择特定颜色的单元格?
- loops - 如何在 jmeter 中继续执行相同的 url n 次?
- php - 登录页面后的 PHP & Session
- google-maps-api-3 - 如何找到所有地方,属于一个区域中的atms等类别,根据半径或一些纬度和经度定义?
- c++ - 如何使用 glReadPixels 和 gluUnproject 生成正确的点坐标?
- reactjs - 身份服务器注册不会重定向回 React 应用程序