MySQL - select - max - group by - efficiency

时间:2013-05-24 21:50:39

标签: mysql select join max

我对MySQL DBMS的性能有疑问。 也许是一件小事。 有两个表,我需要得到如下结果:

     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'

我目前的查询是:

   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 

适合我,但在我看来它应该是一种更有效的方法。

这只是更大查询的关键部分。

托马斯

1 个答案:

答案 0 :(得分:0)

要使此联接有效,player_id中的VISITS必须有一个索引。看看

`CREATE INDEX` 

这里。

要检查查询效率,您始终可以使用:

EXPLAIN SELECT /* your select here */

此外,如果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

但你的原始查询完全没问题。如果省略列,请确保完全理解GROUP BY以及GROUP BY中未包含的列的后果。这可能会在其他查询中产生意想不到的后果(其中相同的id并不意味着相同的名称,即。)