简单的select语句中的java.sql.Types.ARRAY

时间:2018-01-19 13:07:31

标签: sql join oracle11g apache-nifi

我有什么:

  • 表“CI”,这里有很多列,ci_id,description,...
  • 表“CI_REL”,ci_id,parent_ci_id,child_ci_id
  • CI_REL中包含多个关系,以显示CI中的一条记录具有多个父级,或CI中的多个子级记录

我需要什么:

加入这两个表,所以我得到了一条富含Sql ARRAY(VARRAY?)的CI记录,用于记录中的父母和子女。

示例:

|id | description | children | parents |
|1  | root        | [2,3]    | null    |
|2  | child1      | [3]      | [1]     |
|3  | child2      | [2]      | [1]     |

为什么我需要这个?我正在使用Apache Nifi将数据提取到Apache Solr中,并且需要为儿童和父母提供多值字段。由于ExecuteSQL正在解释sql ResultSet,并以我需要的方式执行查找java.sql.Types.ARRAY,我想要一个select,实际上以某种方式返回它。顺便说一句:我没有任何可能使用PL / SQL,希望这不会让答案变得不可能......

谢谢! 海宁

1 个答案:

答案 0 :(得分:2)

您可以在相关子查询中使用CAST( COLLECT( ... ) AS ... )生成您的集合:

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE CI ( id, description ) AS
SELECT 1, 'root' FROM DUAL UNION ALL
SELECT 2, 'child1' FROM DUAL UNION ALL
SELECT 3, 'child2' FROM DUAL;

CREATE TABLE CI_REL ( ci_id, child_ci_id, parent_ci_id ) AS
SELECT 1, 2, NULL FROM DUAL UNION ALL
SELECT 2, 3, 1    FROM DUAL UNION ALL
SELECT 3, NULL, 2 FROM DUAL;

CREATE TYPE NumberList IS TABLE OF Number(8,0);

查询1

SELECT c.*,
       ( SELECT CAST(
                  COLLECT(
                    DISTINCT child_ci_id
                    ORDER BY LEVEL
                  ) AS NumberList
                )
          FROM  CI_REL r
          WHERE child_ci_id IS NOT NULL
          START WITH r.ci_id = c.id
          CONNECT BY PRIOR child_ci_id = ci_id
       ) AS children,
       ( SELECT CAST(
                  COLLECT(
                    DISTINCT parent_ci_id
                    ORDER BY LEVEL
                  ) AS NumberList
                )
          FROM  CI_REL r
          WHERE parent_ci_id IS NOT NULL
          START WITH r.ci_id = c.id
          CONNECT BY PRIOR parent_ci_id = ci_id
        ) AS parents
FROM   CI c

<强> Results

| ID | DESCRIPTION | CHILDREN | PARENTS |
|----|-------------|----------|---------|
|  1 |        root |      2,3 |         |
|  2 |      child1 |        3 |       1 |
|  3 |      child2 |          |     2,1 |