子查询返回多行

时间:2013-07-10 20:49:08

标签: sql oracle

我的SELECT语句中有一个子查询返回多行,但我需要两个值。无论如何使用逗号连接多个值以使外部查询认为子查询只返回一个值?

我的查询示例:

select o.id,
   (select v.value v from values v join attributes a on v.att_id=a.att_id where a.att_id='100' and v.id=o.id)
from objects o
where o.class_id='GGzX';

提前致谢!

3 个答案:

答案 0 :(得分:2)

尝试使用此查询,可能会很有用(点击here来测试查询):

CREATE TABLE TEST1(
ID INT);

CREATE TABLE TEST2(
    ID INT,
    TXT VARCHAR2(100));

INSERT INTO TEST1 VALUES(1);
INSERT INTO TEST1 VALUES(2);
INSERT INTO TEST1 VALUES(3);

INSERT INTO TEST2 VALUES(1,'A');
INSERT INTO TEST2 VALUES(1,'B');
INSERT INTO TEST2 VALUES(2,'C');
INSERT INTO TEST2 VALUES(3,'A');
INSERT INTO TEST2 VALUES(3,'B');
INSERT INTO TEST2 VALUES(3,'C');

/* HERE IS THE QUERY!!!*/
SELECT A.ID, 
(SELECT listagg(B.TXT,',' ) WITHIN GROUP (ORDER BY B.ID)
FROM TEST2 B WHERE B.ID = A.ID
) AS CONTATENATED_FIELD
FROM TEST1 A;

注意:listagg适用于11.X版本,有关详细信息,请参阅此link

根据您的查询,您可能需要以下内容:

select o.id,
(SELECT listagg(v.value,',' ) WITHIN GROUP (ORDER BY v.value) from values v join attributes a on v.att_id=a.att_id where a.att_id='100' and v.id=o.id)
from objects o
where o.class_id='GGzX';

答案 1 :(得分:0)

只需添加GROUP BY a.att_id或限制查询

即可
select o.id,
   (select v.value val from values v join attributes a on v.att_id=a.att_id
 where a.att_id='100' and v.id=o.id GROUP BY a.att_id)
from objects o
where o.class_id='GGzX';

OR


select o.id,
   (select v.value val from values v join attributes a on v.att_id=a.att_id
 where a.att_id='100' and v.id=o.id LIMIT 1)
from objects o
where o.class_id='GGzX';

或者只是按任何分隔符

对值进行分组
select o.id,
   (select group_concat( v.value SEPARATOR ' / ') val from values v join attributes a on v.att_id=a.att_id
 where a.att_id='100' and v.id=o.id GROUP BY a.att_id)
from objects o
where o.class_id='GGzX';

答案 2 :(得分:0)