如果创建表时同时设置了主键,OceanBase 数据库会默认创建一个唯一索引。以下面的 SQL 为例:
为表增加索引可以通过 CREATE INDEX 语句。OceanBase 能在普通表和分区表上创建索引,索引可以是本地索引或者全局索引。同时索引可以是唯一索引或者普通索引,如果是分区表的唯一索引,唯一索引必须包含表分区的拆分键。
MySQL 租户里,索引名称在表范围内不能重复,查看索引可以通过命令 SHOW INDEXES 。
在 MySQL 租户里,新增索引还有一种方法,SQL 语法格式如下:
- 示例:对分区表新增索引
obclient> create table t1(id bigint not null primary key ,name varchar(50) not null);
Query OK, 0 rows affected (0.06 sec)
obclient> show indexes from t1;
*************************** 1. row ***************************
Table: t1
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: id
Cardinality: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment: available
Index_comment:
Visible: YES
1 row in set (0.00 sec)
obclient> create table t3(
id bigint not null primary KEY
, name varchar(50)
, gmt_create timestamp not null default current_timestamp
obclient> alter table t3 add unique key t3_uk (name) local;
ERROR 1503 (HY000): A UNIQUE INDEX must include all columns in the table's partitioning function
obclient> alter table t3
add unique key t3_uk (name, id) LOCAL
, add key t3_ind3(gmt_create) global;
Query OK, 0 rows affected (18.03 sec)
obclient> show indexes from t3;
删除索引
删除索引的语法格式如下:
obclient> alter table t3 drop key t3_uk, drop key t3_ind3;
Query OK, 0 rows affected (0.07 sec)