我有下面的查询,它返回一定时间间隔的结果集,如1分钟,10分钟,1小时等。[以下工作例如持续10分钟。]
select MemoryUsage, TransactionTime, moduleid
from tbl_trnmemoryusage
where TransactionTime between (now() - interval 10 minute ) and now()
order by TransactionTime asc;
要求
如果上面的查询没有返回任何内容,那就不是该持续时间内的数据,那么返回基于" TransactionTime"柱
if above_query returns null
then
select MemoryUsage, TransactionTime, moduleid
from tbl_trnmemoryusage
order by TransactionTime desc limit 1;
答案 0 :(得分:1)
SELECT
COALESCE(t.MemoryUsage, t2.MemoryUsage),
COALESCE(t.TransactionTime, t2.TransactionTime),
COALESCE(t.moduleid, t2.moduleid)
FROM (
SELECT *
FROM tbl_trnmemoryusage
ORDER BY TransactionTime DESC
LIMIT 1
) t2
LEFT JOIN (
SELECT *
FROM tbl_trnmemoryusage
WHERE TransactionTime BETWEEN (NOW() - INTERVAL 10 MINUTE) and NOW()
ORDER BY TransactionTime ASC
) t
ON 1
答案 1 :(得分:1)
你试过这种方式吗?
select MemoryUsage, TransactionTime, moduleid
from tbl_trnmemoryusage
where TransactionTime >=
IF((Select Count(*) from (
select MemoryUsage, TransactionTime, moduleid
from tbl_trnmemoryusage
where TransactionTime between (now() - interval 10 minute ) and now()
) As Tbl1) > 0,
(now() - interval 10 minute),
(Select Max(TransactionTime)
from tbl_trnmemoryusage))
order by TransactionTime asc;
答案 2 :(得分:1)
您可以将UNION ALL与SELECT语句一起使用,只有在给定范围内找不到行时才会返回一行。
select MemoryUsage, TransactionTime, moduleid
from tbl_trnmemoryusage
where TransactionTime between (now() - interval 10 minute ) and now()
union all
select * from (
select MemoryUsage, TransactionTime, moduleid
from tbl_trnmemoryusage
where not exists (
select 1 from tbl_trnmemoryusage
where TransactionTime between (now() - interval 10 minute ) and now()
)
order by TransactionTime desc limit 1
) b
order by TransactionTime asc
如果您不关心性能或结果集很小,则可以跳过NOT EXISTS条件并让UIONN DISTINCT
消除重复。请注意,它还会删除数据库中已存在的所有重复项。
select MemoryUsage, TransactionTime, moduleid
from tbl_trnmemoryusage
where TransactionTime between (now() - interval 1 minute ) and now()
union distinct
select * from (
select MemoryUsage, TransactionTime, moduleid
from tbl_trnmemoryusage
order by TransactionTime desc limit 1
) b
order by TransactionTime asc