如果一个条件为真,如何选择某些行,如果另一个条件为真,则如何选择其他行?

时间:2013-08-19 08:21:09

标签: sql oracle oracle11g

如果某个条件为真,我想从表中选择一些行,如果另一个条件为真,则选择其他条件,然后(最后)选择其他一些行。主要问题是我想从命令行插入一个参数,如下所示:

if exists(select a.* from a
left join b on a.id=b.id
where b.id=:MY_PARAMETER)
else if exists
(select c.* from c where c.id=:Another_Parameter)
else
(select * from b)

我知道我做错了什么,但我无法弄清楚是什么。我尝试使用CASE-Then但我找不到适应解决方案的方法。任何的想法?感谢

PS:我读过其他一些关于此类事情的帖子,但正如我解释的那样,我遇到了这方面的困难。

< ===被修改=====>

希望我澄清一些事情:

select
case when b.id=6
then (select * from a)
else (select a.* from a join b
on b.aid=a.aid)
end
from a join b
on b.aid=a.aid
join c
on b.id=c.bid
where b.id=:num

在这种情况下,问题是它不允许在CASE语句中返回多个值。

3 个答案:

答案 0 :(得分:1)

联合应该做得很好,例如你的第一个例子(这只有在表a,b和c具有相似的列顺序和类型时才有效):

select a.* from a
left join b on a.id=b.id
where b.id=:MY_PARAMETER
UNION
select c.* from c where c.id=:Another_Parameter
and not exists(select a.* from a
left join b on a.id=b.id
where b.id=:MY_PARAMETER)
UNION
select b.* from b
where not exists
(select c.* from c where c.id=:Another_Parameter
and not exists(select a.* from a
left join b on a.id=b.id
where b.id=:MY_PARAMETER))
and not exists (select a.* from a
left join b on a.id=b.id
where b.id=:MY_PARAMETER)

为了构建更有效的查询,我需要更具体的例子。


SELECT a.* FROM a
INNER JOIN b ON a.id = b.id
WHERE b.id = :MY_PARAMETER
UNION
SELECT a.* FROM a
INNER JOIN b ON a.id = b.id
INNER JOIN c ON b.id = c.bid
WHERE NOT EXISTS (SELECT * FROM b WHERE
                 b.id = :MY_PARAMETER)
AND c.id = :Another_Parameter

答案 1 :(得分:1)

感谢Mikhail,解决我问题的正确查询是:

select a.*
from a
join b
on a.id1=b.id2
where b.id1= :value and exists 
(select b.id1 from bwhere b.id1 = :value)
union all
select *
from a
where exists (select * from c where c.id1=5 and c.id2=:value)

答案 2 :(得分:0)

你试过DECODE吗?

Select DECODE(EXISTS(*Case1*),*First case column*,
    DECODE(EXISTS(*Case2*),*Second case column*,*Default case column*)) FROM ...