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

时间:2016-03-13 22:47:16

标签: sql arrays postgresql postgresql-9.4

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[...]的情况下添加此复合数组,那么正确的语法是什么?

2 个答案:

答案 0 :(得分:1)

添加新的嵌套级别时,使用文字字符串将不太可读:

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. 您需要根据嵌套级别引用" ARRAY转义的每个级别。
  2. 这种模式看起来像是试图将OO世界引入数据库。它可能比标准化版本更难维护和更慢。 \
  3. 如果需要,您可以使用Related question.引用字符串文字。
  4. 使用ROW<?php $last_y = date("Y") -1; ?> <option value='Annual'>Annual - <?php echo $last_y; ?></option> 可以更容易地找到每个级别开始和停止的位置。

答案 1 :(得分:1)

再次问问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)\"\"}\")"}

SQL Fiddle.

我完全同意目前的建议:多级嵌套行类型通常很复杂且效率低下。考虑规范化。

我对你上一个问题的回答更多: