如何正确优化此查询?

xoefb8l8  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(281)

我正在尝试优化以下查询。我用explain来解决问题,但它一直以非索引查询的形式出现在我们的日志中。我错过了什么?我已经在引用的所有列上创建了索引,但它仍在显示。

select `users`.`nickname`, `users`.`userId`, `userdata`.`avatarUpdatedAt` 
from `users` 
inner join `userdata` on `userdata`.`userId` = `users`.`userId` 
order by `lastActivity` desc 
limit 28
+---+---+---+---+---+---+---+---+---+---+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+---+---+---+---+---+---+---+---+---+---+
| 1 | SIMPLE | users | index | PRIMARY,userId | lastActivity | 8 | NULL | 28 |  |
| 1 | SIMPLE | userdata | eq_ref | userdata_userid_unique | userdata_userid_unique | 8 | prod.users.userId | 1 | Using index condition |
+---+---+---+---+---+---+---+---+---+---+

# Time: 200703  6:14:18

# User@Host: prod[prod] @ localhost [127.0.0.1]

# Thread_id: 17988  Schema: prod  QC_hit: No

# Query_time: 0.000201  Lock_time: 0.000011  Rows_sent: 28  Rows_examined: 56

# Rows_affected: 0  Bytes_sent: 1039

# Full_scan: Yes  Full_join: No  Tmp_table: No  Tmp_table_on_disk: No

# Filesort: No  Filesort_on_disk: No  Merge_passes: 0  Priority_queue: No
rm5edbpk

rm5edbpk1#

如果您有一个包含数百万行的大表,最好是 where 条件筛选出数据以使查询运行更快。
索引将有助于检索数据,所以只有索引并不能使查询运行得更快。

select 
    u.nickname, 
    u.userId, 
    ud.avatarUpdatedAt 
from users u
inner join userdata ud
on ud.userId = u.userId
where ud.avatarUpdatedAt >= '2020-01-01'
and ud.avatarUpdatedAt <= '2020-05-01'
order by lastActivity desc

相关问题