如果第一个表为空,如何使查询从另一个表中进行选择。
这是我正在使用SQL Server的C#程序中的当前查询。
private const string sql = @'SELECT TOP (1) (LOCALTIME) from dbo.[devicemessage] order by (localtime) desc;
因此,这段代码要做的是从在localtime desc中排列的前1行获取localtime列中的值;最新时间。
我想做的是这样的:
If dbo.[devicemessage] is empty select top (1) (localtime) from dbo.[devicemessagehistory] order by (localtime) desc,
if table dbo.[devicemessage] not empty, get from dbo.[devicemessage].
正如我在C#中使用它一样,是否可以在一个查询字符串中完成此操作。
只需将两个表与一个not exists
条件合并即可。这使您可以从同一查询的2个表中进行选择,但是如果第一个表中没有行,则仅从第二个表中给出结果:
select top 1 localtime
from (
select localtime
from dbo.[devicemessage]
union all
select localtime
from dbo.[devicemessagehistory]
where not exists (select 1 from dbo.[devicemessage])
) X
order by localtime desc;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句