对于 InnoDB 和 MyISAM 表,MySQL 可以使用类似于创建常规索引的语法创建空间索引,但需要使用 SPATIAL 关键字。空间索引中的列必须声明为 NOT NULL。以下示例演示了如何创建空间索引:For InnoDB and MyISAM
tables, MySQL can create spatial indexes using syntax similar to
that for creating regular indexes, but using the
SPATIAL keyword. Columns in spatial indexes
must be declared NOT NULL. The following
examples demonstrate how to create spatial indexes:
使用
CREATE TABLE:WithCREATE TABLE:CREATE TABLE geom (g GEOMETRY NOT NULL SRID 4326, SPATIAL INDEX(g));
使用
ALTER TABLE:WithALTER TABLE:CREATE TABLE geom (g GEOMETRY NOT NULL SRID 4326); ALTER TABLE geom ADD SPATIAL INDEX(g);
使用
CREATE INDEX:WithCREATE INDEX:CREATE TABLE geom (g GEOMETRY NOT NULL SRID 4326); CREATE SPATIAL INDEX g ON geom (g);
SPATIAL INDEX 创建一个 R 树索引。对于支持空间列非空间索引的存储引擎,引擎会创建一个 B 树索引。在空间值上创建 B 树索引对于精确值查找是有用的,但对于范围扫描则不适用。SPATIAL INDEX creates an R-tree index. 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.
优化器可以使用在受 SRID 限制的列上定义的空间索引。有关更多信息,请参见 第 13.4.1 节,“空间数据类型”,以及 第 10.3.3 节,“空间索引优化”。The optimizer can use spatial indexes defined on columns that are SRID-restricted. For more information, see Section 13.4.1, “Spatial Data Types”, and Section 10.3.3, “SPATIAL Index Optimization”.
有关索引空间列的更多信息,请参见 第 15.1.15 节,“CREATE INDEX 语句”。For more information on indexing spatial columns, see Section 15.1.15, “CREATE INDEX Statement”.
要删除空间索引,请使用 ALTER
TABLE 或 DROP INDEX:To drop spatial indexes, use ALTER
TABLE or DROP INDEX:
使用
ALTER TABLE:WithALTER TABLE:ALTER TABLE geom DROP INDEX g;
使用
DROP INDEX:WithDROP INDEX:DROP INDEX g ON geom;
示例:假设表 geom 包含超过 32,000 个几何体,它们存储在类型为 GEOMETRY 的列 g 中。该表还有一个 AUTO_INCREMENT 列 fid 用于存储对象 ID 值。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.
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)
要在列 g 上添加空间索引,请使用以下语句:To add a spatial index on the column g, use
this statement:
mysql> ALTER TABLE geom ADD SPATIAL INDEX(g);
Query OK, 32376 rows affected (4.05 sec)
Records: 32376 Duplicates: 0 Warnings: 0