SQL只评估某些情况某些情况下db2和sybase
问题描述:
我需要在我的查询中某个where子句仅在某些情况下进行评估。SQL只评估某些情况某些情况下db2和sybase
例如,
select * from employee e where e.age=14 and e.salary=1000
在上述查询我需要薪水其中当e.age > 30
我使用DB2和SYBASE仅被评估子句。
答
使用OR
如果你想添加的条件查询,不应该总是适用,就像这样:
SELECT *
FROM employee e
WHERE e.age = 14 OR (e.age>30 AND e.salary=1000)
这会给你e.age = 14
所有结果不管什么工资及一切结果e.age>30
其中,工资是1000
+0
不是真的,这里是需要的 – user2713255
+0
@ user2713255我更新了我的答案。 – waka
答
做这个
Select * from employee e where e.age=14 or e.age>30 and e.salary=1000
答
如何:
select *
from employee e
where e.age = 14 -- change to any age you want, then ...
and (-- if age > 30 then we also need to check salary
(e.age > 30 and e.salary = 1000)
or
-- if age <= 30 then we don't care about salary
(e.age <= 30)
)
的关键是具有互补的where
条款覆盖表中的所有行(e.age > 30
或e.age <= 30
)。
另一种可能性(应Sybase ASE的工作,不知道DB2语法)...
select *
from employee e
where e.age = 14 -- change to any age you want, then ...
and e.salary = case when e.age > 30
then 1000 -- when e.age > 30, e.salary=1000
else e.salary -- when e.age <= 30, e.salary=e.salary
end
'选择从员工的E *其中e.age = 14,e.salary = 1000和e.age> 30;' – SriniV