Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何正确优化此查询?_Mysql_Sql_Mariadb - Fatal编程技术网

Mysql 如何正确优化此查询?

Mysql 如何正确优化此查询?,mysql,sql,mariadb,Mysql,Sql,Mariadb,我正在尝试优化以下查询。我使用EXPLAIN进行故障排除,但它一直以非索引查询的形式出现在日志中。我错过了什么?我已经在引用的所有列上创建了索引,但它仍在显示 select `users`.`nickname`, `users`.`userId`, `userdata`.`avatarUpdatedAt` from `users` inner join `userdata` on `userdata`.`userId` = `users`.`userId` order by `lastAc

我正在尝试优化以下查询。我使用EXPLAIN进行故障排除,但它一直以非索引查询的形式出现在日志中。我错过了什么?我已经在引用的所有列上创建了索引,但它仍在显示

select `users`.`nickname`, `users`.`userId`, `userdata`.`avatarUpdatedAt` 
from `users` 
inner join `userdata` on `userdata`.`userId` = `users`.`userId` 
order by `lastActivity` desc 
limit 28

如果您有一个包含数百万行的大表,最好使用
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 
索引将有助于检索数据,所以只有索引并不会使查询运行得更快

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 
选择
u、 绰号,
u、 用户ID,
ud.avatarUpdatedAt
来自用户u
内部连接用户数据ud
在ud.userId=u.userId上
其中ud.avatarUpdatedAt>='2020-01-01'

和ud.avatarUpdatedAt如果您没有“where”条件,那么索引列对您没有帮助。查询需要0.0002秒,您对此感到困扰吗?听起来您需要停止在日志中查找未编制索引的查询。有些查询不需要索引。这里有一些关于索引不用于连接的错误答案。不是真的。但我怀疑您的表/限制太小(28行?),以至于查询优化程序已经计算出,只扫描表会更快。添加一些其他条件,或者添加更多行,您可能会发现不同。它确实使用了
索引(lastActivity)
,但不使用不存在的
WHERE
子句。它将其用于订购方
。它确实为另一个表使用了索引。此外,slowlog显示它只触及了每个表中的28行;当你有28个极限时,很难打败它!归根结底,“非索引查询”抱怨是站不住脚的。“在所有列上创建索引”可能会伤害到你。
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