简体   繁体   English

在SQL中:当“无结果”从查询返回时显示一些默认结果

[英]In SQL: When 'no results' return from a query show some default results

I'm using Postgres to get results from a table. 我正在使用Postgres从表中获取结果。 I want to use SQL to solve a problem. 我想用SQL来解决问题。

When my postgresql query returns no results, I would like some default row results to appear. 当我的postgresql查询没有返回任何结果时,我想要显示一些默认的行结果。 I am using Jasper-reports, so I don't have a lot of tools to catch the event where there are no results, and then deliver default results. 我正在使用Jasper报告,因此我没有很多工具来捕获没有结果的事件,然后提供默认结果。

When the first query DOES show results I do not want the default results to appear. 当第一个查询显示结果时,我不希望显示默认结果。 Currently I'm trying to use a UNION but I want the second query after the Union command to ONLY happen if the first query shows 0 results. 目前我正在尝试使用UNION,但是如果第一个查询显示0结果,我希望在Union命令之后发生第二个查询。

Can this be done in SQL? 这可以在SQL中完成吗?

You could try a CTE: 你可以试试CTE:

with fooresults as
(
select c1, c2 from foo
)

select c1, c2 from fooresults
union
select c1, c2 from blah
where (select count(*) from fooresults)=0

OR you can test for empty fooresults without counting: 或者你可以测试空的fooresults而不计算:

 where not exists (select 1 from fooresults) 

PS And of course you could add any conditions required when you instantiate the CTE: PS当然,您可以在实例化CTE时添加所需的任何条件:

      select c1, c2 from foo where .... <some conditions>

Don't do a count to check the existence of a row as it will count the whole table. 不要count检查行的存在,因为它将计算整个表。 In instead use exists 相反,使用exists

select c1, c2, c3
from t
union
select 1, 2, 3
where not exists (select * from t)
SELECT * 
FROM table1
UNION ALL
SELECT *
FROM table2
WHERE 0 = (
   SELECT count(table1.id)
   FROM Table1
   GROUP BY table1.id)

By head, feels ugly though... 通过头,但感觉丑陋......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM