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

时间:2013-04-12 13:16:52

标签: sql postgresql union

我正在使用Postgres从表中获取结果。我想用SQL来解决问题。

当我的postgresql查询没有返回任何结果时,我希望显示一些默认的行结果。我正在使用Jasper报告,因此我没有很多工具来捕获没有结果的事件,然后提供默认结果。

当第一个查询显示结果时,我不希望显示默认结果。目前我正在尝试使用UNION,但我希望在Union命令之后的第二个查询仅在第一个查询显示0结果时发生。

可以在SQL中完成吗?

3 个答案:

答案 0 :(得分:5)

您可以尝试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

或者你可以测试空的fooresults而不计算:

 where not exists (select 1 from fooresults) 

P.S。当然,您可以在实例化CTE时添加所需的任何条件:

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

答案 1 :(得分:4)

不要执行count检查是否存在行,因为它会计算整个表。而是使用exists

select c1, c2, c3
from t
union
select 1, 2, 3
where not exists (select * from t)

答案 2 :(得分:2)

SELECT * 
FROM table1
UNION ALL
SELECT *
FROM table2
WHERE 0 = (
   SELECT count(table1.id)
   FROM Table1
   GROUP BY table1.id)

头部,虽然感到丑陋......