[英]Oracle query: compare values in table to other values in same table
我们有一个基于Oracle的系统,用于管理设备并将其详细信息和配置存储在称为“ configs”的表中。 每个设备由几个模块组成,每个模块的配置另存为逗号分隔的字符串。 例如:
device_id module values
1 1 3,4,2,3
1 2 4,1,3,4
1 3 2,1,2,3
1 4 6,4,2,1
1 5 1,4,2,3
1 6 1,3,4,4
2 1 3,4,2,3
2 2 4,1,3,4
2 3 2,3,2,3
2 4 6,4,2,1
2 5 1,8,2,3
2 6 1,3,4,4
3 1 3,4,2,3
3 2 4,1,3,4
3 3 2,1,2,3
3 4 6,4,2,1
3 5 1,4,2,3
3 6 1,3,4,4
4 1 3,4,2,3
4 2 4,1,3,4
4 3 2,1,2,4
4 4 6,4,2,1
4 5 1,4,2,3
4 6 1,3,7,4
我需要审核系统,并确定其配置与已知的正确配置不匹配的每个模块。 理想情况下,假设设备1的配置是我的好配置,我想运行这样的查询:
select device_id,module
from configs
where values != (select values from configs where device_id = 1)
但这返回一个错误:
ORA-01427: single-row subquery returns more than one row
如果我将查询更改为此,它将起作用:
select device_id,module
from configs
where values = (select values from configs where device_id = 1 and module = 1);
但是然后我必须为“模块”的每个值运行查询。
我想做的是编写一个查询,使我能够一口气做到这一点。 有人暗示我可以使用游标语句,但是我一直在努力寻找“假人的Oracle游标”类型的文章,到目前为止,我所研究的内容都没有对我有所帮助,包括http://docs.oracle.com/ cd / B28359_01 / server.111 / b28286 / expressions006.htm#SQLRF52057 。 有人可以建议吗?
谢谢。
模块编号是否必须匹配? 即(设备1的)模块2的配置是否被视为(某些其他设备的)模块3的良好配置?
如果是这样,则有几种良好的配置(这就是为什么数据库说single-row subquery returns more than one row
)。 您必须考虑到这一点:
select device_id, module
from configs
where values not in (select values from configs where device_id = 1)
如果不是,则必须选择一个与所考虑的行匹配的行,例如:
select device_id, module
from configs c1
where values = (
select values
from configs c2
where device_id = 1
and c1.module = c2.module
)
产生错误的查询正试图在单个值上下文中比较项目列表。 您需要将您的“!=”更改为“ not in”,它应该可以工作。 这是调整后的查询:
select device_id, module
from configs
where values not in (select values from configs where device_id = 1)
如果我没看错,我想您可以使用以下方法:
DECLARE
device_string VARCHAR2 (100);
BEGIN
FOR i IN (SELECT * FROM configs WHERE device_id = 1)
LOOP
SELECT listagg(device_id, ';')
WITHIN GROUP (ORDER BY device_id)
INTO device_string
FROM configs
WHERE values != i.values AND module=i.module;
DBMS_OUTPUT.PUT_LINE(
' Bad config for module ' || i.module ||
' in devices: ' || device_string);
END LOOP;
END;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.