For 对于InnoDB and MyISAM tables, MySQL can create spatial indexes using syntax similar to that for creating regular indexes, but using the SPATIAL keyword. InnoDB和MyISAM表,MySQL可以使用与创建常规索引类似的语法创建空间索引,但使用SPATIAL关键字。Columns in spatial indexes must be declared 空间索引中的列必须声明为NOT NULL. The following examples demonstrate how to create spatial indexes:NOT NULL。以下示例演示了如何创建空间索引:
With 使用CREATE TABLE:CREATE TABLE:
CREATE TABLE geom (g GEOMETRY NOT NULL SRID 4326, SPATIAL INDEX(g));
With 使用ALTER TABLE:ALTER TABLE:
CREATE TABLE geom (g GEOMETRY NOT NULL SRID 4326); ALTER TABLE geom ADD SPATIAL INDEX(g);
With 使用CREATE INDEX:CREATE INDEX:
CREATE TABLE geom (g GEOMETRY NOT NULL SRID 4326); CREATE SPATIAL INDEX g ON geom (g);
SPATIAL INDEX creates an R-tree index. 创建R树索引。For storage engines that support nonspatial indexing of spatial columns, the engine creates a B-tree index. A B-tree index on spatial values is useful for exact-value lookups, but not for range scans.对于支持空间列的非空间索引的存储引擎,该引擎会创建一个B树索引。空间值的B树索引对于精确的值查找很有用,但对于范围扫描则不有用。
The optimizer can use spatial indexes defined on columns that are SRID-restricted. 优化器可以使用在受SRID限制的列上定义的空间索引。For more information, see Section 11.4.1, “Spatial Data Types”, and Section 8.3.3, “SPATIAL Index Optimization”.有关更多信息,请参阅第11.4.1节,“空间数据类型”和第8.3.3节,“空间索引优化”。
For more information on indexing spatial columns, see Section 13.1.15, “CREATE INDEX Statement”.有关索引空间列的更多信息,请参阅第13.1.15节,“CREATE INDEX语句”。
To drop spatial indexes, use 要删除空间索引,请使用ALTER TABLE or DROP INDEX:ALTER TABLE或DROP INDEX:
With 使用ALTER TABLE:ALTER TABLE:
ALTER TABLE geom DROP INDEX g;
With 使用DROP INDEX:DROP INDEX:
DROP INDEX g ON geom;
Example: Suppose that a table 示例:假设一个表geom contains more than 32,000 geometries, which are stored in the column g of type GEOMETRY. The table also has an AUTO_INCREMENT column fid for storing object ID values.geom包含32000多个几何图形,这些几何图形存储在GEOMETRY类型的g列中。该表还有一个AUTO_INCREMENT列fid,用于存储对象ID值。
mysql>DESCRIBE geom;+-------+----------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+----------+------+-----+---------+----------------+ | fid | int(11) | | PRI | NULL | auto_increment | | g | geometry | | | | | +-------+----------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) mysql>SELECT COUNT(*) FROM geom;+----------+ | count(*) | +----------+ | 32376 | +----------+ 1 row in set (0.00 sec)
To add a spatial index on the column 要在g, use this statement:g列上添加空间索引,请使用以下语句:
mysql> ALTER TABLE geom ADD SPATIAL INDEX(g);
Query OK, 32376 rows affected (4.05 sec)
Records: 32376 Duplicates: 0 Warnings: 0