以每小时用户登录时间形式对数据进行分组的 MySQL 查询,以及获取近期一小时登录用户的记录?


为此,你可以将子查询与 JOIN 条件结合使用。语法如下:

SELECT yourTablevariableName.*
FROM
(
   SELECT MAX(UNIX_TIMESTAMP(yourDateTimeColumnName)) AS anyAliasName
   FROM getLatestHour
   GROUP BY HOUR(UserLoginDateTime)
) yourOuterVariableName
JOIN yourTableName yourTablevariableName
ON UNIX_TIMESTAMP(yourDateTimeColumnName) = yourOuterVariableName.yourAliasName
WHERE DATE(yourDateTimeColumnName) = 'yourDateValue';

为了理解上述语法及其产生的结果,我们先创建一个表。创建表的查询如下:

mysql> create table getLatestHour
   -> (
   -> UserId int,
   -> UserName varchar(20),
   -> UserLoginDateTime datetime
   -> );
Query OK, 0 rows affected (0.68 sec)

你现在可以使用 insert 命令向表中插入一些记录。这些记录是用户记录,包括用户登录日期和时间。查询如下:

mysql> insert into getLatestHour values(100,'John','2019-02-04 10:55:51');
Query OK, 1 row affected (0.27 sec)
mysql> insert into getLatestHour values(101,'Larry','2019-02-04 12:30:40');
Query OK, 1 row affected (0.16 sec)
mysql> insert into getLatestHour values(102,'Carol','2019-02-04 12:40:46');
Query OK, 1 row affected (0.20 sec)
mysql> insert into getLatestHour values(103,'David','2019-02-04 12:44:54');
Query OK, 1 row affected (0.17 sec)
mysql> insert into getLatestHour values(104,'Bob','2019-02-04 12:47:59');
Query OK, 1 row affected (0.15 sec)

使用 select 语句显示表中的所有记录。查询如下:

mysql> select *from getLatestHour;

以下是输出:

+--------+----------+---------------------+
| UserId | UserName | UserLoginDateTime   |
+--------+----------+---------------------+
|    100 | John     | 2019-02-04 10:55:51 |
|    101 | Larry    | 2019-02-04 12:30:40 |
|    102 | Carol    | 2019-02-04 12:40:46 |
|    103 | David    | 2019-02-04 12:44:54 |
|    104 | Bob      | 2019-02-04 12:47:59 |
+--------+----------+---------------------+
5 rows in set (0.00 sec)

以下是如何按小时对数据进行分组并获取最近一小时的记录的查询。查询如下:

mysql> SELECT tbl1.*
   -> FROM (
   -> SELECT MAX(UNIX_TIMESTAMP(UserLoginDateTime)) AS m1
   -> FROM getLatestHour
   -> GROUP BY HOUR(UserLoginDateTime)
   -> ) var1
   -> JOIN getLatestHour tbl1
   -> ON UNIX_TIMESTAMP(UserLoginDateTime) = var1.m1
   -> WHERE DATE(UserLoginDateTime) = '2019-02-04';

以下是输出:

+--------+----------+---------------------+
| UserId | UserName | UserLoginDateTime   |
+--------+----------+---------------------+
|    100 | John     | 2019-02-04 10:55:51 |
|    104 | Bob      | 2019-02-04 12:47:59 |
+--------+----------+---------------------+
2 rows in set (0.05 sec)

更新于:2019 年 7 月 30 日

256 次浏览

开启您的 职业生涯

完成课程,获得认证

立即开始
广告