如何选择当前时间戳十分钟内所有记录于 MySQL 中?
可以使用以下语法选择当前时间戳十分钟内所有记录−
SELECT *FROM yourTableName WHERE yourColumnName > = DATE_SUB(NOW(),INTERVAL 10 MINUTE);
为了理解上述语法,让我们创建一个表。创建表的查询如下−
mysql> create table users -> ( -> Id int NOT NULL AUTO_INCREMENT, -> UserName varchar(20), -> UserLastseen datetime, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.91 sec)
使用 insert 命令在表中插入一些记录。查询如下−
mysql> insert into users(UserName,UserLastseen) values('Larry','2019-01-15 02−45−00'); Query OK, 1 row affected (0.15 sec) mysql> insert into users(UserName,UserLastseen) values('Sam',now()); Query OK, 1 row affected (0.25 sec) mysql> insert into users(UserName,UserLastseen) values('Mike','2019-01-15 02−30−00'); Query OK, 1 row affected (0.15 sec) mysql> insert into users(UserName,UserLastseen) values('Bob','2019-01-15 15−02−00'); Query OK, 1 row affected (0.23 sec) mysql> insert into users(UserName,UserLastseen) values('David','2019-01-15 14−55−00'); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中所有记录。查询如下−
mysql> select *from users;
输出如下−
+----+----------+---------------------+ | Id | UserName | UserLastseen | +----+----------+---------------------+ | 1 | Larry | 2019-01-15 02−45−00 | | 2 | Sam | 2019-01-15 15−01−52 | | 3 | Mike | 2019-01-15 02−30−00 | | 4 | Bob | 2019-01-15 15−02−00 | | 5 | David | 2019-01-15 14−55−00 | +----+----------+---------------------+ 5 rows in set (0.00 sec)
以下是如何选择当前时间戳十分钟内所有记录的查询−
mysql> select *from users -> where UserLastseen> = date_sub(now(),interval 10 minute);
输出如下−
+----+----------+---------------------+ | Id | UserName | UserLastseen | +----+----------+---------------------+ | 2 | Sam | 2019-01-15 15−01−52 | | 4 | Bob | 2019-01-15 15−02−00 | | 5 | David | 2019-01-15 14−55−00 | +----+----------+---------------------+ 3 rows in set (0.00 sec)
广告