【问题标题】:Execute different statements in one query on the condition根据条件在一个查询中执行不同的语句
【发布时间】:2016-11-24 01:10:42
【问题描述】:

假设我们有两个用户,ID = 1 和 ID = 2

我知道当前用户的ID,我需要根据ID 执行不同的select 语句。

if ID = 1
select a from table1
else if ID = 2
select b from table2
else
select c from table3

有没有办法将此逻辑放入单个 SQL 查询中?

【问题讨论】:

  • ID 是 table1、table2、table3 或变量中的列,并且这些表列中的任何一个名称为 ID?

标签: sql oracle conditional-statements


【解决方案1】:

您可以在适当的where 条件下使用union。

select a from table1 where id = 1
union all
select b from table2 where id = 2
union all
select c from table3 where id not in (1,2)

或者如果表格可以joined

select 
case when t1.id = 1 then t1.a
     when t2.id = 2 then t2.b
else t3.c end
from table1 t1
join table2 t2 on t1.id = t2.id
join table3 t3 on t1.id = t3.id

【讨论】:

  • 据我了解,如果每次只满足一个条件,这种方法会导致冗余计算。
  • @Sloth 这个计算需要几毫秒。如果条件始终为假,CBO 足够聪明,不会获取数据(如果 id = 2,则表示 1=2)
  • @EvgeniyK。想象一下,如果条件评估足够昂贵。我的例子很简单
  • 发布你正在尝试做的事情
  • 看,对于我的用户,我需要获取他的角色列表并检查该列表是否与另一个角色列表相交。如果满足之前的条件,我不想评估下一个条件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 2020-05-30
  • 2016-11-02
  • 1970-01-01
  • 2015-07-27
  • 2012-12-08
  • 2020-10-04
相关资源
最近更新 更多