Select 行嵌套 table 列满足条件

Select lines where nested table column meets a condition

v 定义如下:create or replace type v is table of numberemp 是一个 table,其中包含一列输入 v.

我想 select v.count 为 3 的行,但我会遇到编译错误。是因为v.count是PL/SQL码吗?

我试过将代码放在匿名块中,但还是不行。

使用游标是唯一的解决方案吗?

 SELECT *
 FROM emp
 WHERE V.COUNT = 3;

谢谢。

我想你在找 cardinality():

CARDINALITY returns the number of elements in a nested table. The return type is NUMBER. If the nested table is empty, or is a null collection, then CARDINALITY returns NULL.

所以你可以这样做:

SELECT *
FROM emp
WHERE cardinality(V) = 3;

快速演示:

create or replace type v is table of number
/

create table emp (id number, v v)
nested table v store as v_tab;

insert into emp (id, v) values (1, v(1));
insert into emp (id, v) values (2, v(1,2));
insert into emp (id, v) values (3, v(1,2,3));
insert into emp (id, v) values (4, v(1,2,3,4));

column v format a30
set feedback 1

SELECT *
FROM emp
WHERE cardinality(V) = 3;

        ID V                             
---------- ------------------------------
         3 V(1, 2, 3)                    

1 row selected. 

我喜欢 Alex 的基数答案,这是另一种方法:

create or replace type num_type as table of number;

create table table_with_num_type
(
ids num_type,
val varchar2(100)
)
nested table ids store as ids_tab ;

insert into table_with_num_type(ids, val) values (num_type(1,2,3), 'TEST1');
insert into table_with_num_type(ids, val) values (num_type(4,5,6,7), 'TEST2');
commit;

select t.val, count(t2.column_value) as num_count
from table_with_num_type t, table(t.ids) t2
group by t.val
having count(t2.column_value) = 3;

结果:

VAL NUM_COUNT
TEST1   3