SQL 如何在oracle中使用带有if条件的select?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5189649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to using select with if condition in oracle?
提问by swathy
My requirement is to get a number from a complex query and check if the num = desiredNum.
我的要求是从复杂查询中获取一个数字并检查 num = requiredNum。
If it is equal to desiredNum, then I must perform another set of select statements,
如果它等于desiredNum,那么我必须执行另一组select语句,
Is there any way I can achieve this in a query rather than writing a function?
有什么方法可以在查询中实现这一点而不是编写函数吗?
Eg:
例如:
select case when val =2
then select val1 from table1
else 'false'
from (select val from table)
Is this possible ??
这可能吗 ??
回答by RichardTheKiwi
select case when val=2 then val1 else val end as thevalue
from table1
I assume you meant that val and val1 are both from the same table, but when val=2, to use val1 instead. If you actually had two tables, and they both have only one recordeach, then
我假设你的意思是 val 和 val1 都来自同一个表,但是当 val=2 时,使用 val1 代替。如果您实际上有两个表,并且每个表都只有一条记录,那么
select
case when val=2
then (select val1 from table1)
else 'false'
end
from table
回答by Daniel Williams
I am not 100% I understand what you need. But I think you could use a union to do this:
我不是 100% 我明白你需要什么。但我认为你可以使用联合来做到这一点:
create table theValues ( theValue integer)
create table table1 ( value1 integer)
create table table2 ( value2 integer)
INSERT INTO theValues (thevalue) VALUES (2)
INSERT INTO table1 ( value1 ) VALUES (17)
INSERT INTO table2 ( value2 ) VALUES (8)
SELECT value1 from table1 WHERE EXISTS (SELECT theValue from theValues WHERE theValue != 2)
UNION ALL
SELECT value2 from table2 WHERE EXISTS (SELECT theValue from theValues WHERE theValue = 2)
In this case the "magic number" is 2. If the theValues table query returns 2, then you get the results from the result from table2, else you get the result from table 1.
在这种情况下,“幻数”是 2。如果 theValues 表查询返回 2,那么您从 table2 的结果中获取结果,否则从 table 1 中获取结果。
Cheers, Daniel
干杯,丹尼尔