Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.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 - Fatal编程技术网

为什么相同的MySQL索引在下面的情况下搜索不同数量的行

为什么相同的MySQL索引在下面的情况下搜索不同数量的行,mysql,sql,Mysql,Sql,我有一张桌子。我们称之为表1 CREATE TABLE table1 ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(100) NOT NULL, entity_id int(11) NOT NULL, created datetime not null, last_modified datetime, PRIMARY KEY (id), KEY entity_idx (entity_id) ); 我已插入实

我有一张桌子。我们称之为表1

CREATE TABLE table1 (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(100) NOT NULL, 
  entity_id int(11) NOT NULL,
  created  datetime not null,
  last_modified datetime,
  PRIMARY KEY (id),
  KEY entity_idx (entity_id)
);
我已插入实体_id 1、2和3的测试数据。1有20行,2有10行,3有5行。id值为1到35

现在我提出以下问题:

explain extended 
select * 
from table1 
where entity_id = 1 and id < 22 
order by id desc limit 3;
如果我将查询条件从id<24更改为id<28,我将得到以下输出:

explain extended 
select * 
from table1 
where entity_id = 1 and id < 28 
order by id desc limit 3;
这两种情况下,MySQL都使用实体_idx作为选择索引。但在第一种情况下,搜索的行数是10,而在第二种情况下,行数是15。实体id仅在实体id列上。因此,在这两种情况下,MySQL都应该搜索相同数量的行(所有行都搜索实体_id 1)。id列上的条件不应更改搜索的行数,因为我们只使用实体id列索引


那么,为什么在这两个查询中搜索的行数不同呢?同样在第一种情况下,输出中的额外列提到“使用where”,但在第二种情况下,输出提到“使用索引条件”。有人能解释一下吗?

MySQL假设扫描速度比查找速度快,而行数不超过10。当
{list}
包含少于或多于10个值时,({list})中的
WHERE列的比较更清楚。
explain extended 
select * 
from table1 
where entity_id = 1 and id < 28 
order by id desc limit 3;
# id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
'1', 'SIMPLE', 'table1', NULL, 'range', 'PRIMARY,entity_idx', 'entity_idx', '8', NULL, '15', '100.00', 'Using index condition'