简体   繁体   English

MySQL-选择-最大-分组-效率

[英]MySQL - select - max - group by - efficiency

I have a question regarding performance of the MySQL DBMS. 我对MySQL DBMS的性能有疑问。 Perhaps a trivial matter. 也许是一件小事。 There are two tables and I need to get result as below : 有两个表,我需要得到如下结果:

     PLAYERS                           VISITS
     ID | PLAYER_NAME                  ID | PLAYER_ID | SEEN
     ----------------                  ---------------------------
     1  | user 1                        1 | 2         | 2012-12-12
     2  | user 2                        2 | 2         | 2012-12-13
     3  | user 3                        3 | 3         | 2012-12-13
     4  | user 4                        4 | 3         | 2012-12-14
                                        5 | 3         | 2012-12-14
                                        6 | 2         | 2012-12-15
RESULT:
ID | PLAYER_NAME | LAST_SEEN  
----------------------------
 1 | user 1      | NULL / 'NEVER'
 2 | user 2      | 2012-12-15
 3 | user 3      | 2012-12-14
 4 | user 4      | NULL / 'NEVER'

My current query is : 我当前的查询是:

   SELECT 
   players.id, 
   players.player_name, 
   MAX(visits.seen) AS last_seen
   FROM players
   LEFT JOIN visits ON players.id = visits.player_id
   GROUP BY players.id,players.player_name 

Works for me but it seems to me that it should be a more efficient method. 对我有用,但在我看来,它应该是更有效的方法。

It's just key part of a larger query. 它只是较大查询的关键部分。

Thomas 汤玛士

To make this join efficient there has to be an index on player_id in VISITS . 为了使这种连接有效,必须在VISITS player_id上有一个索引。 Look into 调查

`CREATE INDEX` 

here. 这里。

To check the query efficiency you can always use: 要检查查询效率,您可以始终使用:

EXPLAIN SELECT /* your select here */

Also if PLAYERS.ID is unique and primary key it's perfectly fine to group only by this id. 另外,如果PLAYERS.ID是唯一且是主键,则仅按此ID分组也可以。

SELECT 
   players.id, 
   players.player_name, 
   MAX(visits.seen) AS last_seen
FROM players
   LEFT JOIN visits ON players.id = visits.player_id
GROUP BY players.id

but your original query is perfectly fine. 但您的原始查询就可以了。 Make sure you fully understand GROUP BY and the consequences for columns not included in GROUP BY if you omit columns. 确保你完全理解GROUP BY和不包含在列的后果GROUP BY如果省略列。 This can have unintended consequences in other queries (where the same id doesn't mean the same name ie) 这可能在其他查询中产生意外的结果(相同的ID并不意味着相同的名称,即)

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

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