如果未找到行,则从过滤器中选择返回值

时间:2013-04-24 13:38:23

标签: sql oracle10g

我需要一个总是返回至少一条记录的select语句。像这样的东西

SELECT id, date FROM mytable WHERE id = <INPUT_ID> AND date = <INPUT_DATE>
UNION ALL
SELECT VALUE_FROM_FILTER(id), VALUE_FROM_FILTER(date) WHERE NOT EXISTS (SELECT * FROM mytable WHERE id = <INPUT_ID> AND date = <INPUT_DATE>)

因此,如果查询返回0行,则返回至少一行包含输入值。 这可能在SQL中吗?

我正在使用Oracle 10.2

<INPUT_ID><INPUT_DATE>只是任何未知值的替代

(基于答案和评论,我将问题修改为更明显)

2 个答案:

答案 0 :(得分:0)

您可以在第一个查询没有返回结果的事实上预测“默认”行:

SELECT id, date FROM mytable WHERE id = @INPUT_ID AND date = @INPUT_DATE
UNION
SELECT @INPUT_ID AS id, @INPUT_DATE AS date FROM DUAL
WHERE NOT EXISTS (SELECT * FROM mytable WHERE id = @INPUT_ID AND date = @INPUT_DATE)

答案 1 :(得分:0)

我并不完全确定,但我认为这就是你想要的:

with t as (select <INPUT ID> as input_id, <INPUT DATE> as input_date from dual)
select input_id, input_date
from t
left join mytable mt on mt.id = t.input_id and mt.date = t.input_date;

使用一些示例数据:

create table mytable (id number, date_fld date);
insert into mytable (id, date_fld) values (1, date '2013-04-24');
insert into mytable (id, date_fld) values (2, date '2013-04-22');
insert into mytable (id, date_fld) values (2, date '2013-04-22');
insert into mytable (id, date_fld) values (2, date '2013-04-23');

...和查询:

with t as (select 1 as input_id, date '2013-04-21' as input_date from dual)
select input_id, input_date
from t
left join mytable mt on mt.id = t.input_id and mt.date_fld = t.input_date;

  INPUT_ID INPUT_DAT
---------- ---------
         1 21-APR-13

with t as (select 1 as input_id, date '2013-04-24' as input_date from dual)
select input_id, input_date
from t
left join mytable mt on mt.id = t.input_id and mt.date_fld = t.input_date;

  INPUT_ID INPUT_DAT
---------- ---------
         1 24-APR-13

with t as (select 2 as input_id, date '2013-04-22' as input_date from dual)
select input_id, input_date
from t
left join mytable mt on mt.id = t.input_id and mt.date_fld = t.input_date;

  INPUT_ID INPUT_DAT
---------- ---------
         2 22-APR-13
         2 22-APR-13

现在我打字了,因为我有一种讨厌的感觉,我正在回答错误的问题,而你真的想将{WHERE}转换成一个新的查询来执行此操作。我担心,查询和应用程序之间的交互不是很清楚。