【问题标题】:How to select some rows if one condition is true and others if another condition is true?如果一个条件为真,如何选择一些行,如果另一个条件为真,如何选择其他行?
【发布时间】:2013-08-19 20:29:10
【问题描述】:

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

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

【问题讨论】:

  • 你的意思是联合查询吗?例如选择 Id,Description From A Where somecondition union Select Id,Description From B Where Someothercondition
  • 不,如果某些条件为真,我想检索一些行,例如,如果 MY_PARAMETER=10,如果 MY_PARAMETER=20 选择其他一些行,如果 MY_PARAMETER 有另一个值来选择一些新行.我不想合并结果。
  • 您可以使用 plsql 并使用传递的参数创建自己的查询,并使用 refcursor 打开它。
  • 感谢您的回复,我是 pl/sql 的新手,所以我想通过 sql 解决这个问题,但是如果您能通过 pl/sql 帮助我解决这个问题,我将非常感谢 :)
  • 那么不,你的意思是 uinion 查询吗? ...

标签: sql oracle oracle11g


【解决方案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

【讨论】:

  • 感谢您的回复,在我的情况下,三个表的参数数量或类型不同。表 A 通过 FK 与表 B 相连,表 B 与表 C 与 FK 相互连接。我将通过命令行输入表 B 的值。如果在 A&B 的 JOIN 中找到该值,我想从 A 中检索一些行,并且如果在 A&B JOIN 中找不到该值但与 C 的特定值相关,则我想从 A 中检索其他一些行(同样,只是不同的行)
  • @AlbanoVito 这简化了它,编辑了一个答案 - 检查第二个查询。
  • 谢谢,我现在明白了,我在 Oracle 中尝试过,但它返回:ORA-00932:不一致的数据类型:预期 - 得到 CLOB
  • 我发现一条信息解释了“您不能在 WHERE 子句中放置 CLOB。”。这是因为“不存在的地方(Select * from..)”吗?
  • @AlbanoVito a.id 和 c.id 列的类型是什么?
【解决方案2】:

感谢 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)

【讨论】:

    【解决方案3】:

    你试过解码吗?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多