postgresql 不使用ARRAY[]的嵌套复合类型的数组

sqxo8psd  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(2)|浏览(149)
CREATE TYPE pencil_count AS(
    pencil_color varchar(30),
    count integer
);

CREATE TYPE pencil_count_with_date(
date_ date,
pencil_count pencil_count[]
);

CREATE TABLE pencils(id serial, pencils_ pencil_count_with_date[]);

INSERT INTO pencils(pencils_) 
VALUES('{"(\"2016-03-13\",{"(\"blue\",1)","(\"red\",2)"})"}');

字符串
如果我想在不使用ARRAY[...]的情况下添加这个复合数组,正确的语法是什么?

wz3gfoph

wz3gfoph1#

当您添加新的嵌套级别时,使用文字字符串将变得可读性较差:

CREATE TYPE pencil_count AS(pencil_color varchar(30)
       ,"count" int);

CREATE TYPE pencil_count_with_date AS(date_ date
                                     ,pencil_count pencil_count[]);

CREATE TABLE pencils(id serial, pencils_ pencil_count_with_date[]);

INSERT INTO pencils(pencils_) 
VALUES('{"(
               \"2016-03-13\",
               \"{
                   \"\"(Blue,5)\"\",
                   \"\"(Red,2)\"\"
               }\"
          )"}');   

SELECT pencils_[1].pencil_count[1].pencil_color
FROM pencils;

字符串

SqlFiddleDemo

备注:
1.你需要引用每个级别,"根据嵌套级别被\转义。
1.这种模式看起来像是试图将OO世界引入数据库。它可能比规范化版本更难维护,也更慢。Related question.
1.如果需要的话,你可以用$$来引用字符串。
1.使用ARRAYROW可以更容易地发现每个级别的开始和停止位置。

wooyq4lh

wooyq4lh2#

再次,问Postgres.扩展的过程为your previous question

CREATE TEMP TABLE pencil_count (
  pencil_color varchar(30)
, count integer
);

CREATE TABLE pencil_count_with_date (
  date_ date
, pencil_count pencil_count[]
);

CREATE TABLE pencils (
  id serial
, pencils_ pencil_count_with_date[]
);

字符串
询问Postgres每个嵌套级别:

INSERT INTO pencil_count VALUES ('red' , 1), ('blue', 2);

SELECT ARRAY(SELECT p FROM pencil_count p)::text AS p_row_arr;

-- with result from above:
INSERT INTO pencil_count_with_date(date_, pencil_count)
VALUES ('2016-04-14', '{"(red,1)","(blue,2)"}')
     , ('2016-04-14', '{"(red,3)","(blue,4)"}');

SELECT ARRAY(SELECT p FROM pencil_count_with_date p)::text AS p2_row_arr;

-- with result from above:
INSERT INTO pencils(pencils_)
VALUES
  ('{"(2016-04-14,\"{\"\"(red,1)\"\",\"\"(blue,2)\"\"}\")"
    ,"(2016-04-15,\"{\"\"(red,3)\"\",\"\"(blue,4)\"\"}\")"}');

SELECT id, pencils_::text FROM pencils;


测试结果:

id | pencils_
---+-------------------------------------------------------
1  | {"(2016-04-14,\"{\"\"(red,1)\"\",\"\"(blue,2)\"\"}\")"
     ,"(2016-04-15,\"{\"\"(red,3)\"\",\"\"(blue,4)\"\"}\")"}


fiddle
老小提琴
到目前为止,我完全同意这个建议:多层嵌套行类型通常是复杂和低效的。
更多关于你上一个问题的回答:

  • 复合类型数组的正确语法

相关问题