假设我们有一张 table DVD:
id title type
1 Star Wars Movie
2 Yellow Submarine Music
3 The Lord of The Rings Movie
4 Black Butterfly Music
我们想获得电影“黑蝴蝶”的 dvd,但如果列表中不存在它,那么我们想获得其他电影。 第一个请求:
Select * from DVDs where type='Movie' and title='Black Butterfly'
如果请求没有返回,则执行第二个请求。
Select * from DVDs where type='Moview'
目前,我正在使用(在 Java 中)2 个查询模板和 2 个对数据库 (Oracle) 的请求。我正在寻找使用 1 个模板和 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';
关于java - 是否可以在一个查询中组合 2 个请求,而第二个请求仅在第一个请求没有带来任何内容时执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47458321/