这个概念是我试图比较2个等值表来查看另一个查询是否具有相同的值,或者它们是否存在于另一个查询中。 我加入表格的方式是: “为table1 a选择a.sth,a.sth2,a.st3,b.value,table2 b,其中a.key = b.valkey” 这将导致显示table1的值列,然后显示table2中的列value2,其中键的键相同。 现在我有另外2个表包含类似的数据,我想检查我的查询结果是否存在于我将为其他表构建的查询中,如: “为table3 a选择a.sth,a.sth2,a.st3,b.value,table4 b,其中a.key = b.valkey”
我想到这样做的唯一方法是使用嵌套的隐式游标。例如:
BEGIN
FOR item IN (select a.sth, a.sth2, a.st3, b.value for table1 a, table2 b where a.key = b.valkey)
LOOP
Begin
FOR item2 IN (select a.sth, a.sth2, a.st3, b.value for table3 a, table4 b where a.key = b.valkey)
LOOP
Begin
if (item1.sth = item2.sth) and (item1.sth2 = item2.sth2) and (item1.sth3 = item2.sth3) and (item1.value = item2.value) Then
dbms_output.put_line("Found and value is the same");
Elsif (item1.sth = item2.sth) and (item1.sth2 = item2.sth2) and (item1.sth3 = item2.sth3) and Not (item1.value = item2.value) Then
dbms_output.put_line("Found but value is different");
Exception When no_data_found then
dbms_output.put_line("item1 was not found in table3");
End;
END LOOP;
End;
END LOOP;
END;
以上只是我想做的伪代码。我可以做这样的事情,还是有更好的性能,我可以使用?我期待着你的建议。
答案 0 :(得分:1)
你不需要游标。通常,基于集合的代码将更好地工作。查询看起来像这样:
select coalesce(a.key, b.valkey) as thekey,
a.sth, a.sth2, a.st3, b.value
(case when a.key is null then 'Not found in a'
when b.key is null then 'Not found in b'
when (a.sth = b.sth) and (a.sth2 = b.sth2) and (a.sth3 = b.sth3) and
(a.value = b.value)
then 'Found and same'
when (a.sth = b.sth) and (a.sth2 = b.sth2) and (a.sth3 = b.sth3) and
(a.value <> b.value)
then 'Found and different'
else 'Other!!!'
end)
from table1 a full outer join
table2 b
on a.key = b.valkey