从嵌套表类型中选择一行

时间:2018-09-10 13:01:07

标签: sql oracle nested-table

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

enter image description here

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;

2 个答案:

答案 0 :(得分:1)

使用表集合表达式将嵌套表中的集合视为表,然后对其进行联接。然后,您可以进行过滤以使每个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) |

答案 1 :(得分:1)

您可以使用分组依据来完成此操作:

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;

请注意,我对表Type使用左联接以显示tel为空的记录。

相关问题