为什么mysql不使用这个空间索引?

时间:2017-11-09 20:05:32

标签: mysql key spatial

MySQL / InnoDB + MyISAM 5.7.20 ......

假设:

mysql> desc city;
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| id        | mediumint(9) | NO   | PRI | NULL    | auto_increment |
| name      | char(30)     | NO   |     | NULL    |                |
| geo       | geometry     | NO   | MUL | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+
mysql> show index from city;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| city  |          0 | PRIMARY  |            1 | id          | A         |      798000 |     NULL | NULL   |      | BTREE      |         |               |
| city  |          1 | geo      |            1 | geo         | A         |      882478 |       32 | NULL   |      | SPATIAL    |         |               |
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

...然而

mysql> explain select distinct name from city where st_distance_sphere(@p, geo) < 5000;
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows   | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-------------+
|  1 | SIMPLE      | city  | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 882478 |   100.00 | Using where |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-------------+

所以很清楚(来自type = ALL)空间索引没有被使用。有人可以向我解释为什么不呢? InnoDB和MyISAM存储引擎都是一样的。

1 个答案:

答案 0 :(得分:0)

按照MySQL documentation。 您必须在WHERE子句中使用MBRContains()或MBRWithin()之类的函数。