ORA-00913: 使用 case when 时值太多

ORA-00913: too many values while using case when

我有一个要求,如果一个条件为真,我应该在查询 Q1 上执行,如果该条件不满足,我应该执行另一个查询 Q2。该查询结果是用户执行搜索的记录。 我在 if 条件下使用 case when 语句,因为 Q1 和 Q2 有多个列要检索,我得到 ORA-00913: too many values 。我开始知道在检索数据时无法执行具有更多列的查询的情况。 谁能建议如何实现这种类型要求。

更新:

我无法给出确切的查询,但可以提供伪代码

select case when c1='1' then 
select c1,c2,c3 from table1
else select c1,c2,c3 from table2  end
from table1;

这里我给出示例数据。

表 1

C1      C2     C3
1       null    1
1       2       null

表 2

C1      C2     C3
1       4       1
1       3       5
2       9       null

当我运行查询您提供的内容时,输出结果如下。

select
    coalesce(table2.c1, table1.c1) c1,
    coalesce(table2.c2, table1.c2) c2,
    coalesce(table2.c3, table1.c3) c3
from table1
    left outer join table2
       on (your keys here)
           and table1.c1 <> '1' -- This gets table1 if c1 = '1';

输出:

C1    C2    C3
1     4      1
1     2      5
2     9      null

但我期待的输出是

C1    C2    C3
1     null   1
1     2      null
2     9      null

希望我解释清楚。

当您使用 case 时,您必须 return 只有一个记录 - 不超过 1 个。为了达到您想要的结果,我会使用左外连接(假设您有一个将 table1 连接到 table2 的方法),但将对 table1.c1 的检查添加到连接条件中,以便 table2 值仅在 c1 <> '1'

时出现
select
    coalesce(table2.c1, table1.c1) c1,
    coalesce(table2.c2, table1.c2) c2,
    coalesce(table2.c3, table1.c3) c3
from table1
    left outer join table2
       on (your keys here)
           and table1.c1 <> '1' -- This gets table1 if c1 = '1';

此解决方案假定 table1 和 table2 相关。如果你不能将它们联系起来,那么听起来几乎就像你可以使用一个 union all ,在其中你从 table1 中获取所有值,其中 c1 = '1' 并将这些值联合到所有 table2 行。如有必要,您只能在 c1 <> '1' 时包含 table2 值。

select c1, c2, c3 from table1 where c1 = '1'
union all
select c1, c2, c3 from table2; -- where c1 <> '1' -- if necessary

更新

根据您的示例数据和预期输出,请使用上面的第二个查询:

select c1, c2, c3 from table1 where c1 = '1'
union all
select c1, c2, c3 from table2 where c1 <> '1'

SQL Fiddle: http://www.sqlfiddle.com/#!4/710f0/1/0