我使用Postgres从一个表中获取结果。我想用SQL来解决一个问题。
当我的postgresql查询没有返回任何结果时,我希望出现一些默认的行结果。我使用Jasper-reports,所以我没有太多的工具来捕捉没有结果的事件,然后提供默认的结果。
当第一个查询显示结果时,我不希望显示默认结果。目前,我正在尝试使用UNION,但我希望Union命令之后的第二个查询仅在第一个查询显示0结果时才发生。
这可以在SQL中实现吗?
发布于 2013-04-12 21:24:39
您可以尝试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或者,您可以测试是否有空的fooresult而不进行计数:
where not exists (select 1 from fooresults) 附注:当然,您可以在实例化CTE时添加所需的任何条件:
select c1, c2 from foo where .... <some conditions>发布于 2013-04-12 21:30:31
不要执行count来检查行是否存在,因为它将计算整个表。而是使用exists
select c1, c2, c3
from t
union
select 1, 2, 3
where not exists (select * from t)发布于 2013-04-12 21:22:30
SELECT *
FROM table1
UNION ALL
SELECT *
FROM table2
WHERE 0 = (
SELECT count(table1.id)
FROM Table1
GROUP BY table1.id)头上,虽然感觉很难看...
https://stackoverflow.com/questions/15972417
复制相似问题