MySQL 数据库索引案例

普通索引: normal ,使用最广泛
唯一索引: unique ,不允许重复的索引,允许有空值
全文索引: full text ,只能用于 MyISAM 表, full text 要用于大量 的内容检索
主键索引: primary key 又称为特殊的唯 索引,不允许有空值
组合索引:为提高 MySQL 效率可建立组合索引
创建数据库,表以及索引

[root@localhost ~]# mysql
MariaDB [(none)]> create database t1;
MariaDB [(none)]> use t1;
MariaDB [t1]> create table mytable( ID INT NOT NULL, username varchar(16) NOT NULL , INDEX indexName (ID) );
# 创建表mytable,包含ID、username列,类型为int、varchar(整型、字符串)、都不允许空值,并创建普通索引indexName,Column_name为ID

显示索引信息

MariaDB [t1]> SHOW INDEX FROM mytable;
+---------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table   | Non_unique | Key_name  | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+---------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| mytable |          1 | indexName |            1 | ID          | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
+---------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
1 row in set (0.00 sec)

删除索引

MariaDB [t1]> drop index indexName ON mytable;
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

MariaDB [t1]> SHOW INDEX FROM mytable;
Empty set (0.00 sec)

使用ALTER 命令添加和删除索引

MariaDB [t1]> alter table mytable add index indext_name (id,username);
# 创建组合索引
MariaDB [t1]> alter table mytable1 add fulltext quanwen (username);
# 创建全文索引(注意:创建全文索引需要MyISAM引擎创建的表才能支持)
MariaDB [t1]> alter table mytable add index putong (ID);
# 创建普通索引
MariaDB [t1]> alter table mytable add unique weiyi (ID);
# 创建唯一索引
MariaDB [t1]> alter table mytable add primary key (ID);
# 创建主键索引

你可能感兴趣的:(数据库,数据库,mysql,sql)