是否可以将 2 个请求合并到一个查询中,而第二个请求仅在第一个请求没有带来任何内容时才执行?

Is it possible to combine 2 requests in one query, while the second one is executed only if the first one doesn't bring anything?

提问人:Micah 提问时间:11/23/2017 更新时间:11/23/2017 访问量:44

问:

假设我们有一个桌面 DVD:

id  title                   type    
 1  Star Wars               Movie
 2  Yellow Submarine        Music
 3  The Lord of The Rings   Movie
 4  Black Butterfly         Music

我们想获得电影“黑蝴蝶”的DVD,但如果列表中不存在它,那么我们想获得其他电影。 Firth 请求:

Select * from DVDs where type='Movie' and title='Black Butterfly'

如果 request 不返回任何内容,则执行第二个请求。

Select * from DVDs where type='Moview'

目前,我正在使用(在 Java 中)2 个查询模板和 2 个对数据库 (Oracle) 的请求。我正在寻找使用 1 个模板和 1 个请求的机会。

java 后备sql

评论


答:

2赞 Gordon Linoff 11/23/2017 #1

您可以执行以下操作:

with b as (
      Select *
      from DVDs
      where type = 'Movie' and title = 'Black Butterfly'
     )
select b.*
from b
union all
select d.*
from dvd
where type = 'Movie' and not exists (select 1 from b);

或者,您可以使用窗口函数:

Select . . .
from (select d.*,
             count(*) filter (where title = 'Black Butterfly') over () as cnt_bb
      from DVDs d
      where type = 'Movie'
     ) d 
where cnt_bb = 0 or title = 'Black Butterfly';
2赞 Emilio Lucas Ceroleni 11/23/2017 #2

尝试:

DO
$do$
BEGIN
IF EXISTS (Select * from DVDs where type='Movie' and title='Black Butterfly') THEN
    Select * from DVDs where type='Movie' and title='Black Butterfly';
ELSE 
   Select * from DVDs where type='Moview';
END IF;
END
$do$

评论

0赞 Micah 11/23/2017
ORA-00900:无效的 SQL 语句