Phone_book
+----+---------+-----------+--------------+
| id | key     | code      |    value     |
+----+---------+-----------+--------------+
| 1  | MAX_VAL | 111       |    reset     |
+----+------+--------------+--------------+
| 2  | MIN_VAL | 222       |    set       |
+----+------+--------------+--------------+
| 3  | MIN_VAL | 0         |    NA        |
+----+---------+-----------+--------------+键和代码组合是主键。
要求:
如果存在键和代码,则返回值。
如果存在键,而代码不存在,则返回代码0的值。
Implementation:
通过使用多个查询实现了这一点。用于JPQL的语法
1) "SELECT param FROM Phone_book param WHERE upper(key)=:paramKey AND code=:estCode";
如果这返回null,则拍摄另一个查询。
2) "SELECT param FROM Phone_book param WHERE upper(key)=:paramKey AND code=:O";
我要找的东西:
我可以通过一个查询或更好的方法来实现这一点吗?
提前谢谢。
发布于 2016-08-24 07:18:19
在Oracle SQL中,以下内容将满足您的需要。无需为此编写PLSQL。
SELECT key,
       nvl(code,0)                            -- This will make sure if code is null then value is 0
FROM Phone_book  
WHERE (key is not NULL AND CODE IS NOT NULL)  -- This will help in fetching value when KEY and CODE is present
OR ( key is not null and code is null);       -- This will help in fetching value  when KEY is present and CODE is null. 发布于 2016-08-24 08:03:35
select 
case 
   when key is not null and code is not null then value
   when key is not null and code is null then 0
end 
from phone_book;发布于 2016-08-24 11:03:22
select value from (
  select value, row_number() over (order by case when code = 0 then 2 else 1 end) rn
    from phonebook pb 
    where upper(key) = :paramKey and (code = :estCode or code = 0))
  where rn = 1选择已请求键和请求的代码或代码0的值。用函数row_number对它们进行适当排序,并取第一个值。
https://stackoverflow.com/questions/39114937
复制相似问题