简体   繁体   English

从MySQL中的表中提取最大值的最佳方法

[英]Best approach to pull max value from a table in mysql

I have a mysql table where the details of check-in activity performed by all the users is captured. 我有一个mysql表,其中捕获了所有用户执行的签入活动的详细信息。 Below is the structure with sample data. 下面是带有示例数据的结构。

Table Name: check_in 表名称:check_in

+-----------+--------------------+---------------------+
|   id      |       user_id      |      time           |
+-----------+--------------------+---------------------+
|   1       |       10001        | 2016-04-02 12:04:02 |
|   2       |       10001        | 2016-04-02 11:04:02 |
|   3       |       10002        | 2016-10-27 23:56:17 |
|   4       |       10001        | 2016-04-02 10:04:02 |
|   5       |       10002        | 2016-10-27 22:56:17 |
|   6       |       10002        | 2016-10-27 21:56:17 |
+-----------+--------------------+---------------------+

On the dashboard, I have to display each user and at what time was their latest check-in activity performed (Sample dashboard view shown below). 在仪表板上,我必须显示每个用户以及他们最新的签到活动在什么时间执行(如下所示的示例仪表板视图)。

User 1's last check-in was at 2016-04-02 12:04:02 用户1的最后一次签到于2016-04-02 12:04:02

User 2's last check-in was at 2016-10-27 23:56:17 用户2的最后一次签到于2016-10-27 23:56:17

What is the best and efficient way to write the query to pull this data? 编写查询以提取此数据的最佳和有效方法是什么? I have written below query, but it is taking 5-8 seconds to complete the execution. 我在下面编写了查询,但是要花5到8秒钟才能完成执行。 Note: This table has hundreds of thousands of rows. 注意:此表有成千上万的行。

select user_id, max(time) as last_check_in_at from check_in group by user_id

Your SQL query look optimized to me. 您的SQL查询对我来说看起来很优化。

The reason for it being slow is probably that you do not have indexes on user_id and time columns. 速度慢的原因可能是您在user_idtime列上没有索引。

Try adding the following indexes to your table: 尝试将以下索引添加到表中:

ALTER TABLE `check_in` ADD INDEX `user_id` (`user_id`)
ALTER TABLE `check_in` ADD INDEX `time` (`time`)

and then execute your SQL query again to see if it makes a difference. 然后再次执行您的SQL查询以查看是否有所不同。

The indexes should allow the SQL engine to quickly group the relevant records by user_id and also quickly determine the maximum time . 索引应允许SQL引擎按user_id快速对相关记录进行分组,并且还可以快速确定最大time

Indexes will also help to quickly sort data by time (as suggested by Rajesh) 索引还有助于按time快速对数据进行排序(如Rajesh所建议)

Simply use order by 只需使用order by
Note:- please don't use time as a column name because may be it should be reserved keywords in any language 注意:-请不要将time用作列名,因为它可能是任何语言的保留关键字

  select chk.user_id user_id, chk.time as last_check_in_at from   
    check_in chk group by chk.user_id ORDER BY chk.time 

You need to use order by in query. 您需要在查询中使用order by。

Please try this query 请尝试这个查询

select `user_id`,`time` as last_check_in_at from check_in group by user_id order by `time` DESC

It works for me. 这个对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM