我有一个sceanrio,其中我需要根据主select语句中的条件从不同的子查询中检索值。我尝试使用Case,但问题是Case不支持多列。有没有什么办法可以解决这个问题,或者有没有其他方法可以解决这个问题。
我在简化查询中的场景
select col1,col2,
case when col3='E01089001' then
(select 1,3 from dual)
else
(select 2,4 from dual)
end
from Table1
where col1='A0529';发布于 2009-03-31 14:42:49
这是另一种编写它的方式,它可能会解决对第二个表的访问次数超过必要次数的问题。
select col1,col2,
case when col3='E01089001' then 1 else 2 end,
case when col3='E01089001' then 3 else 4 end
end
from Table1, dual
where col1='A0529';您的示例使用了一个明显简化的子查询,因此这个版本看起来有点傻;根本没有理由使用DUAL连接。但在实际查询中,您可能有一个类似于SELECT a, b FROM otherTable WHERE someCondition的子查询。因此,您可能希望使用实际的列名而不是数字文字,使用实际的表名而不是dual,并将子查询条件移到最终的WHERE子句中。
发布于 2009-03-31 12:39:57
如果每个案例只允许一列,那么您可能需要两个案例:
select col1,col2,
case when col3='E01089001' then
(select 1 from dual)
else
(select 2 from dual)
end,
case when col3='E01089001' then
(select 3 from dual)
else
(select 4 from dual)
end
from Table1
where col1='A0529';我希望我不需要告诉你,当数据库表变得很大时,这种东西的伸缩性不是很好。
发布于 2009-03-31 12:57:33
Case不支持条件检查中的多列
CASE WHEN A=X AND B=Y THEN ... END您在示例中尝试做的是将一个表(两列)返回到一个需要一列的结果集中: col1,col2,(col3,col4)。
需要分别返回: col1、col2、col3、col4
select
col1,
col2,
case when col3='E01089001' then (select 1 from dual) else (select 3 from dual) end,
case when col3='E01089001' then (select 2 from dual) else (select 4 from dual) end
from Table1 where col1='A0529';https://stackoverflow.com/questions/700658
复制相似问题