简体   繁体   English

MySQL查询-为什么在这种情况下不使用索引?

[英]MySQL query - why doesn't it use the index in this case?

MySQL query (ver 5.1.61) MySQL查询(5.1.61版)

SELECT alerts.*,
       devices.user_id
  FROM alerts
       left JOIN devices
          ON alerts.device_id = devices.id
 WHERE    devices.name = 'myval'

There is an index on "alerts.device_id" MySQL in Explain does not use the index, it shows type "ALL" and rows being the full count of rows in the table. 在“ alerts.device_id”上有一个索引,Explain中的MySQL不使用该索引,它显示类型“ ALL”,并且行是表中行的完整计数。

I can't understand why it doesn't use this index. 我不明白为什么它不使用此索引。 What am I missing? 我想念什么?

Thanks! 谢谢!

The index are not getting picked, because you have not used it, neither in the select nor in the where clause. 由于未在select或where子句中使用索引,因此未选择索引。

You need to add an index on device.name 您需要在device.name上添加索引

You can do one thing to force the engine to consider the index if it is a primary key and its value if is more than 0, like : 您可以执行一件事来强制引擎考虑索引(如果它是主键,并且其值大于0),例如:

SELECT alerts.*,
       devices.user_id
  FROM alerts
       left JOIN devices
          ON alerts.device_id = devices.id
 WHERE    devices.name = 'myval' and alerts.deviceid>0

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

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