0

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

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>只是任何未知值的替代品

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

4

2 回答 2

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}成一个新的查询来做这个。恐怕查询和应用程序之间的交互对我来说不是很清楚。

于 2013-04-24T14:25:58.560 回答
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)
于 2013-04-24T13:53:12.923 回答