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

标签 java sql postgresql

假设我们有一张 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/

相关文章:

sql - Amazon Athena 从指令中获取所有文件而不是一个文件

postgresql - PostgreSQL 中 pgScript 的用途是什么?

java - Android:如何创建一个加载栏,文本一半是一种颜色,一半是另一种颜色

mysql - 如何通过where子句中的计算来优化sql查询速度

java SimpleDateFormat.Parse

php - 简单的 MySQL 调用在特定键处选择整数不起作用?

postgresql - 为什么我在 postgresql 中看不到用户权限?

python - Mac 上安装 Odoo 无法执行命令 LESSC

java - 将 switch 重写为数组

Java Swing : adding a JTextField (never used anywhere) randomly makes the screen go white