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

时间:2017-11-23 14:57:54

标签: java sql postgresql

假设我们有一张桌子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'

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

Select * from DVDs where type='Moview'

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

2 个答案:

答案 0 :(得分:2)

你可以这样做:

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';

答案 1 :(得分: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$