首页 > 解决方案 > 执行查询以比较两个值时出现异常

问题描述

在执行查询以比较两列的比率并显示是否其中一列比另一列更严重时,我收到 ORA-01427 异常

这是数据集。这是模拟数据。数据库表1中的数据量很大

col1 col2   col3 col4 col5 col6
c1   c1test 85   85   I    5
c2   c2test 85   85   I    3
c3   c3test 85   85   E    6
c4   c4test G1   G1   E    7
c5   c5test G1   G1   E    5
c6   c6test G1   G1   E    8
c7   c7test G1   G1   I    3
c8   c8test G1   G1   G    7

表2

col1  col2  col3  col4  col5
85    85    D     I      3
85    85    D     E      5
G1    G1    D     E      5
G1    G1    D     I      3
G1    G1    D     G      5
G1    G1    E     I      2
G1    G1    E     E      2
85    85    E     I      3

预期结果 我们需要将table2 的col5 的值与table1 的col6 进行比较,找出table1 的col6 中较大的值并显示记录。只需要对 col3 等于 D 值进行比较。

col1 col2   col3 col4 col5 col6   
c1   c1test 81   81   I    5
c3   c3test 81   81   E    6
c4   c4test G1   G1   E    7
c6   c6test G1   G1   E    8
c8   c8test G1   G1   G    7

我正在使用以下查询

Select * from table1 where 
col6 > (select col5 from 
table2 where col3='D'
and col1=table1.col3
and col2=table1.col4
and col4=table1.col5

这会引发 ora-01427 异常。你能不能得到预期的输出。

标签: sqloracle

解决方案


您的子查询返回多行。您可以使用min()ormax()来解决这个问题。我不确定您真正想要哪种逻辑:

Select t1.*
from table1 t1
where t1.col6 > (select max(t2.col5)
                 from table2 t2
                 where t2.col3 = 'D' and
                       t2.col1 = t1..col3 and
                       t2.col2 = t1.col4 and
                       t2.col4 = t1.col5
                );

推荐阅读