postgres oracle 兼容,PostgreSQL嵌套表(兼容oracle)

oracle中的嵌套表是某些行的集合,它在主表中表示为其中的一列。对主表中的每一条记录,嵌套表可以包含多个行。

通俗地说,嵌套表就是表中的表,把一个表中的字段定义为一个表,这个字段表的数据存储在外部的一个表中。嵌套表可以有效地代替多个表之间的连接。

嵌套表有点类似可变数组,在oracle使用嵌套表是因为可变数组没办法被索引,但是在pg中可以使用gin索引来加速数组的扫描,同时pg也可以实现嵌套表。

https://www.cndba.cn/foucus/article/3885

SQL> CREATE OR REPLACE TYPE type1 AS TABLE OF VARCHAR2(30);

2 /

Type created.

SQL> CREATE TABLE nested_table (id NUMBER, col1 type1)

NESTED TABLE col1 STORE AS col1_tab; 2

Table created.

插入数据:

https://www.cndba.cn/foucus/article/3885

INSERT INTO nested_table VALUES (1, type1('A'));

INSERT INTO nested_table VALUES (2, type1('B', 'C'));

INSERT INTO nested_table VALUES (3, type1('D', 'E', 'F'));

COMMIT;

查询:

https://www.cndba.cn/foucus/article/3885https://www.cndba.cn/foucus/article/3885

SQL> SELECT * FROM nested_table;

ID COL1

---------- ------------------------

1 MY_TAB_T('A')

2 MY_TAB_T('B', 'C')

3 MY_TAB_T('D', 'E', 'F')

SQL> SELECT id, COLUMN_VALUE FROM nested_table t1, TABLE(t1.col1) t2;

ID COLUMN_VALUE

---------- ------------------------

1 A

2 B

2 C

3 D

3 E

3 F

6 rows selected.

—pg

pg中可以使用数组加上复合类型的方法实现嵌套表。

创建复合类型:https://www.cndba.cn/foucus/article/3885

bill=# create type type1 as (c1 int, c2 int, c3 text, c4 timestamp);

CREATE TYPE

bill=# create table tt1 (id int, info text, nst type1[]);

CREATE TABLE

bill=# insert into tt1 values (1,'test',array['(1,2,"abcde","2018-01-01 12:00:00")'::type1, '(2,3,"abcde123","2018-01-01 12:00:00")'::type1]);

INSERT 0 1

查询:

bill=# select * from tt1;

id | info | nst

----+------+----------------------------------------------------------------------------------

1 | test | {"(1,2,abcde,/"2018-01-01 12:00:00/")","(2,3,abcde123,/"2018-01-01 12:00:00/")"}

(1 row)

我们可以使用unnest函数来拆解数组里面的内容:

bill=# select id,info,unnest(nst) from tt1;

id | info | unnest

----+------+--------------------------------------

1 | test | (1,2,abcde,"2018-01-01 12:00:00")

1 | test | (2,3,abcde123,"2018-01-01 12:00:00")

(2 rows)

bill=# select id,info,(unnest(nst)).* from tt1;

id | info | c1 | c2 | c3 | c4

----+------+----+----+----------+---------------------

1 | test | 1 | 2 | abcde | 2018-01-01 12:00:00

1 | test | 2 | 3 | abcde123 | 2018-01-01 12:00:00

(2 rows)

bill=# select id,info,(unnest(nst)).c1 from tt1;

id | info | c1

----+------+----

1 | test | 1

1 | test | 2

(2 rows)

版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值