我希望在我的数据中获得一小时前的最新旧值,但是当我执行此查询时
SELECT locid, value
FROM table2
WHERE date_sub(t_stamp, interval 1 hour)
and locid = '2815'
order by t_stamp desc
我得到了所有的价值观。我该如何解决这个问题?
输出应为
locid | value
2815 | 13.0
答案 0 :(得分:4)
以下查询将获取当前小时并从中减去一小时,然后将其与t_stamp
小时进行比较。
SELECT locid, value
FROM table2
WHERE DATE(t_stamp) = DATE(CURRENT_DATE)
AND HOUR(t_stamp) = HOUR(CURRENT_TIME) -1
AND locid = '2815'
ORDER BY t_stamp desc
LIMIT 1
或者您可能正在寻找以下查询:
SELECT locid, value
FROM table2
WHERE t_stamp <= DATE_SUB(NOW(), INTERVAL 1 HOUR)
AND locid = '2815'
ORDER BY t_stamp desc
LIMIT 1
答案 1 :(得分:0)
只需在查询中添加LIMIT即可返回第一行。
SELECT locid, value
FROM table2
WHERE date_sub(t_stamp, interval 1 hour)
and locid = '2815'
order by t_stamp desc limit 1
答案 2 :(得分:0)
使用LIMIT 1仅返回最高值