arrays - Postgres - 具有复合类型数组的 CRUD 操作
问题描述
我刚刚发现的 Postgres 的一个非常简洁的特性是定义的能力composite type
——在他们的文档中也称为ROWS
和RECORDS
。考虑以下示例
CREATE TYPE dow_id AS
(
tslot smallint,
day smallint
);
现在考虑下表
CREATE SEQUENCE test_id_seq INCREMENT 1 MINVALUE 1 MAXVALUE 2147483647 START 1 CACHE 1;
CREATE TABLE test_simple_array
(
id integer DEFAULT nextval('test_id_seq') NOT NULL,
dx integer []
);
CREATE TABLE test_composite_simple
(
id integer DEFAULT nextval('test_id_seq') NOT NULL,
dx dow_id
);
CREATE TABLE test_composite_array
(
id integer DEFAULT nextval('test_id_seq') NOT NULL,
dx dow_id[]
);
前两个表的 CRUD 操作相对简单。例如
INSERT INTO test_simple_array (dx) VALUES ('{1,1}');
INSERT INTO test_composite_simple (dx) VALUES (ROW(1,1));
array of records/composite types
但是,当表具有as in时,我无法弄清楚如何执行 CRUD 操作test_composite_array
。我努力了
INSERT INTO test_composite_array (dx) VALUES(ARRAY(ROW(1,1),ROW(1,2)));
消息失败
错误:“ROW”处或附近的语法错误
和
INSERT INTO test_composite_array (dx) VALUES("{(1,1),(1,2)}");
消息失败
错误:列“{(1,1),(1,2)}”不存在
和
INSERT INTO test_composite_array (dx) VALUES('{"(1,1)","(1,2)"}');
这似乎有效,尽管它让我感到困惑,因为随后
从 test_composite_array 中选择 dx
返回似乎是字符串结果的结果,{"(1,1),(1,2)}
尽管还有进一步的查询,例如
SELECT id FROM test_composite_array WHERE (dx[1]).tslot = 1;
作品。我还尝试了以下
SELECT (dx[1]).day FROM test_composite_array;
UPDATE test_composite_array SET dx[1].day = 99 WHERE (dx[1]).tslot = 1;
SELECT (dx[1]).day FROM test_composite_array;
哪个有效,而
UPDATE test_composite_array SET (dx[1]).day = 99 WHERE (dx[1]).tslot = 1;
失败。我发现我正在弄清楚如何通过反复试验来操作 Postgres 中的记录/复合类型数组 - 尽管 Postgres 文档通常非常出色 - 文档中似乎没有明确讨论这个主题。我非常感谢任何可以向我指出有关如何在 Postgres 中操作复合类型数组的权威讨论的人。
除此之外,在使用此类数组时是否有任何意外的陷阱?
解决方案
你需要方括号ARRAY
:
ARRAY[ROW(1,1)::dow_id,ROW(1,2)::dow_id]
警告:复合类型是一个很棒的特性,但是如果你过度使用它们会让你的生活变得更加艰难。一旦你想在WHERE
orJOIN
条件中使用复合类型的元素,你就做错了,你会受苦。规范化关系数据有充分的理由。
推荐阅读
- objective-c - 在 UIContainerView 中为 2 个 UIViewController 设置动画
- rest - SharePoint rest api 以获取组成员的完整详细信息
- node.js - 节点 https 客户端 'GET_SERVER_HELLO:sslv3 警报握手失败',但在浏览器中有效
- rxjs - 错误:rxjs/operator/debounceTime 没有导出的成员 'debounceTime'
- reactjs - 使用 React-Router 在 Reactjs 中重定向
- php - 更新记录 Zoho api v2 符号
- android - SimpleXML - 如何?
- c# - 尝试动态更改标签文本时应用程序卡住
- php - PHP 为 json_encode 编码 html
- r - Quantmod 资产负债表货币信息