MySQL笔记2——索引

目录

索引的概念

索引的分类

创建索引

删除索引


  • 索引的概念

索引是对数据库表中的一列或多列的值进行排序后的一种结构,能够提高查询速度。

  • 索引的分类

    分类解释
    普通索引

    由KEY或者INDEX定义,是MySql中的基本索引类型,可以创建在任何数据类型中,

    其值是否唯一由约束条件决定

    唯一索引由UNIQUE 定义的索引,该索引所在的字段的值必须唯一
    全文索引

    由FULLEXT定义的索引,它只能创建在CHAR、VARCHAR、或者TEXT类型的字段上

    现在只有MyISAM支持全文索引

    单列索引

    指的是在表中的单个字段上创建索引,它可以是普通索引、唯一索引或者全文索引,

    只要保证该索引只对应表中的一个字段即可

    多列索引

    指在表中的多个字段创建索引,只有在查询条件中使用了这些字段中的第一个字段时,

    该索引才会被使用。

    空间索引

    由SPACIAL定义的索引,它只能穿建在空间数据类型的字段上。创建空间索引的字段,

    必须声明为NOT NULL。

  • 创建索引

方法解释
创建表的时候创建索引
create table 表名 (字段名 数据类型 [约束],
                   字段名 数据类型 [约束],
                   ...
                   字段名 数据类型 [UNIQUE|FULLTEXT|SPATIAL] INDEX|KEY [别名] (字段名1[长度] [ASC|DESC]);
  1. UNIQUE:可选参数,表示唯一索引
  2. FULLTEXT:可选参数,表示全文索引
  3. SPATIAL:可选参数,表示空间索引
  4. INDEX和KEY:二选一,用来表示字段的索引
  5. 别名:可选参数,表示创建的索引的名称
  6. 字段名1:指定索引对于字段的名称
  7. 长度:可选参数,用于表示索引的长度
  8. ASC和DESC:可选参数,分别表示升序和降序
在已存在的表上创建索引
alter table 表名 add [UNIQUE|FULLTEXT|SPATIAL] INDEX 索引名称 (字段名[(长度)] [ASC|DESC]);

方法举例
创建表的时候创建索引
  1. 创建普通索引
    create table b1 (
    id int,
    name varchar(20),
    score float,
    index(id));
  2. 创建唯一索引
    create table b2 (
    id int not null,
    name varchar(20) not null,
    score float,
    unique index bieming(id ASC));
  3. 创建全文索引
    create table b3 (
    id int not null,
    name varchar(20) not null,
    score float,
    fulltext index bieming(name));
  4. 创建单列索引
    create table b4 (
    id int not null,
    name varchar(20) not null,
    score float,
    index danliebieming(name(20)));
  5. 创建多列索引
    create table b5 (
    id int not null,
    name varchar(20) not null,
    score float,
    index multi (id,name(20)));
  6. 创建空间索引
    create table b6 (
    id int,
    space geometry not null,
    spatial index sp(space))ENGINE=MyISAM;

    查看索引是否被使用

    explain select * from b1 where id=1 \G;
在已存在的表上创建索引
create table b1(
id int(20) not null,
name varchar(255) not null,
grade float)
create table b2 (
bookid int not null,
bookname varchar(255) not null,
content varchar(255) null)ENGINE=MyISAM;
create table b3 (
g geometry not null)ENGINE=MyISAM;
  1. 创建普通索引
    create index putongsy on b1(id);
  2. 创建唯一索引
    crate unique index weiyisy on b1(id);
  3. 创建单列索引
    create index danliesy on b1(id);              
  4. 常见多列索引
    create index duoliesy on b1(id,name);     
  5. 创建全文索引
    create fulltext index quanwensy on b2(content);     
  6. 创建空间索引
    create spatial index kongjiansy on b3(g);     
  • 删除索引

    方法举例
    使用ALTER TABLE删除索引
    alter table 表名 drop index 索引名; 

    使用DROP INDEX 删除索引
    drop index 索引名 on 表名;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值