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 -> );
现在,您可以使用insert命令在表中插入一些记录。记录是包括用户登录日期和时间的用户记录。查询如下-
mysql> insert into getLatestHour values(100,'John','2019-02-04 10:55:51'); mysql> insert into getLatestHour values(101,'Larry','2019-02-04 12:30:40'); mysql> insert into getLatestHour values(102,'Carol','2019-02-04 12:40:46'); mysql> insert into getLatestHour values(103,'David','2019-02-04 12:44:54'); mysql> insert into getLatestHour values(104,'Bob','2019-02-04 12:47:59');
使用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)