我的 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';
提前致谢!
试试这个查询,也许会有用(点击这里测试查询):
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 版本,请参阅此链接了解更多信息。
根据您的查询,您可能需要这样的东西:
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';
只需添加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';