如果第一个表为空,如何使查询从另一个表中进行选择。
这是我的C#程序中的当前查询,我正在使用SQL Server。
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#中使用它一样,是否可以在一个查询字符串中完成它。
答案 0 :(得分:3)
选择isnull()
或coalesce()
将得到您的max()
devicemessage
LOCALTIME
(如果有),如果没有,将选择您的devicemessagehistory
。
如果您只有两个条件,isnull()
就足够了,但是如果您有多个条件,我建议您使用coalesce()
。
select isnull(
(select max(LOCALTIME) from [devicemessage]),
(select max(LOCALTIME) from [devicemessagehistory]))
select coalesce(
(select max(LOCALTIME) from [devicemessage]),
(select max(LOCALTIME) from [devicemessagehistory]))
使用order by
select isnull(
(select TOP 1 localtime from dbo.[devicemessage] order by localtime desc),
(select TOP 1 localtime from dbo.[devicemessagehistory] order by localtime desc))
答案 1 :(得分:2)
只需将两个表与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;