【问题标题】:select one row from nested table type从嵌套表类型中选择一行
【发布时间】:2019-02-14 22:11:29
【问题描述】:

我的问题是从该列类型中仅选择一条记录作为默认值。

create type t_tel as table of number;

create table users_tel(
user_id number,
user_name varchar2(100),
tel t_tel
) nested table tel store as tel_table;

insert into users_tel(user_id, user_name, tel) values (1, 'Amir', t_tel(987,654,321));

select * from users_tel;

【问题讨论】:

    标签: sql oracle nested-table


    【解决方案1】:

    您可以使用 group by 来做到这一点:

    select u.user_id, u.user_name, min(t.column_value) def_tel from users_tel u left join table(u.tel) t on 1=1 group by u.user_id, u.user_name;

    请注意,我使用 left join 和表格类型来显示 tel 为空的记录。

    【讨论】:

      【解决方案2】:

      使用表集合表达式将嵌套表中的集合视为一个表并在其上连接。然后你可以过滤得到每user_id一行:

      SQL Fiddle

      Oracle 11g R2 架构设置

      create type t_tel as table of number;
      
      create table users_tel(
        user_id number,
        user_name varchar2(100),
        tel t_tel
      ) nested table tel store as tel_table;
      
      insert into users_tel(user_id, user_name, tel)
        SELECT 1, 'Amir',  t_tel(987,654,321) FROM DUAL UNION ALL
        SELECT 2, 'Dave',  t_tel(123,456)     FROM DUAL UNION ALL
        SELECT 3, 'Kevin', t_tel()            FROM DUAL;
      

      查询 1

      SELECT user_id,
             user_name,
             tel_no
      FROM   (
        SELECT u.*,
               t.column_value AS tel_no,
               ROW_NUMBER() OVER ( PARTITION BY u.user_id ORDER BY ROWNUM ) AS rn
        FROM   users_tel u
               LEFT OUTER JOIN
               TABLE( u.tel ) t
               ON ( 1 = 1 )
      )
      WHERE  rn = 1
      

      Results

      | USER_ID | USER_NAME | TEL_NO |
      |---------|-----------|--------|
      |       1 |      Amir |    987 |
      |       2 |      Dave |    123 |
      |       3 |     Kevin | (null) |
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-28
        • 2020-12-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多