如果查询没有返回任何行,如何保证一行?

时间:2017-02-10 09:56:43

标签: sql ms-access ms-access-2010

我有以下联合查询:

select dataItem,1 as sortOrder from table1
union
select dataItem,2 from table2
order by sortOrder

如果第一个select查询返回一行而第二个select查询没有返回任何行,那么我得到以下结果:

dataItem | sortOrder
---------+----------
12345    | 1

我想确保总是至少有一行,这样如果seconde查询没有返回任何行,我们就会:

dataItem | sortOrder
---------+----------
12345    | 1
0        | 2

我怎样才能实现这一目标?

2 个答案:

答案 0 :(得分:2)

想法是添加max(dataItem)或0的并集。不确定ACCESS语法

select dataItem,1 as sortOrder from table1
union
select dataItem, 2 from table2
union 
select iif(max(dataItem) is null, 0, max(dataItem)), 2 from table2
order by sortOrder

答案 1 :(得分:0)

如果union然后query

,您可以再添加一个if there is any row in table2no rowsreturn row with default values支票select dataItem,1 as sortOrder from table1 union select dataItem,2 from table2 union select 0,2 where not exists (select 1 from table2) order by sortOrder
import os
print(os.path.isdir("/home/el"))