Mysql 最近 2 小时的结果集

Mysql result set for last 2 hours

看看这个查询:

SELECT attempt_time, u.username
  FROM login_attempts l 
  JOIN user u ON u.user_id = l.user_id AND  u.username = 'jhone' 

+---------------------+---------------+
| attempt_time        | username      |
+---------------------+---------------+
| 2021-07-27 16:06:48 | jhone         |
| 2021-07-27 16:34:33 | jhone         |
| 2021-07-27 16:34:46 | jhone         |
| 2021-07-27 16:39:53 | jhone         |
| 2021-07-27 18:33:30 | jhone         |
| 2021-07-27 18:34:13 | jhone         |
+---------------------+---------------+

我只需要 attempt_time 最后 2 小时:

这是我试过的方法,但结果总是给出空集。

SELECT attempt_time, u.username
  FROM login_attempts l 
    JOIN user u ON u.user_id = l.user_id AND  u.username = 'jhone' 
WHERE NOW() BETWEEN l.attempt_time AND NOW() - INTERVAL 2 HOUR;

谁能告诉我为什么我的查询不起作用?

我认为 WHERE 子句中的逻辑不正确。试试这个版本:

SELECT attempt_time, u.username
FROM login_attempts l 
INNER JOIN user u ON u.user_id = l.user_id
WHERE u.username = 'jhone'  AND
      l.attempt_time BETWEEN NOW() AND NOW() - INTERVAL 2 HOUR;

注意如果futute中没有数据,WHERE子句可以简化为:

WHERE u.username = 'jhone'  AND l.attempt_time > NOW() - INTERVAL 2 HOUR

过去 2 小时意味着:

WHERE l.attempt_time BETWEEN NOW() - INTERVAL 2 HOUR AND NOW();

或者也许:

WHERE l.attempt_time >= NOW() - INTERVAL 2 HOUR;

如果 NOW() 之后没有行。