0

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

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 语句中返回多个值。

4

3 回答 3

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
于 2013-08-19T08:59:00.050 回答
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)
于 2013-08-19T12:29:10.420 回答
0

你试过解码吗?

Select DECODE(EXISTS(*Case1*),*First case column*,
    DECODE(EXISTS(*Case2*),*Second case column*,*Default case column*)) FROM ...
于 2013-08-19T12:10:51.910 回答