如果没有结果那么另一个查询,可以合并到一个查询?

时间:2016-08-24 05:17:09

标签: sql oracle jpql

Phone_book
+----+---------+-----------+--------------+
| id | key     | code      |    value     |
+----+---------+-----------+--------------+
| 1  | MAX_VAL | 111       |    reset     |
+----+------+--------------+--------------+
| 2  | MIN_VAL | 222       |    set       |
+----+------+--------------+--------------+
| 3  | MIN_VAL | 0         |    NA        |
+----+---------+-----------+--------------+

密钥和代码组合是主键。

要求:

如果存在KEY和CODE,则返回VALUE。

如果KEY存在且CODE不存在,则返回CODE 0的值。

实施

使用多个查询实现此目的。使用的语法是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";

我在寻找什么:

我可以通过一个查询或更好的方式实现这一目标吗?

提前致谢。

4 个答案:

答案 0 :(得分:2)

在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. 

答案 1 :(得分:0)

MySQL 相关,因为问题最初被标记为MySQL

你可以尝试一下:

SELECT 
defaultTable.`key`,
COALESCE(queryTable.`value`,defaultTable.`value`) AS v
FROM
(
    SELECT 
    `key`,
    `value`
    FROM Phone_book 
    WHERE UPPER(`key`) = ?
    AND `code` = 0
) AS defaultTable

LEFT JOIN 
(
    SELECT 
    `key`,
    `value`
    FROM Phone_book 
    WHERE UPPER(`key`) = ?
    AND `code` = ?
) AS queryTable
ON defaultTable.`key` = queryTable.`key`;

注意:用提供的值替换问号。

如果不存在所提供的keycode值的任何记录,则queryTable.value将为NULL

因此,COALESCE会从defaulTable中选择值。

答案 2 :(得分:0)

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;

答案 3 :(得分:0)

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正确排序并获取第一个值。