索引

1、普通索引(index)
  1、使用规则
    1、可设置多个字段
    2、字段值无约束
    3、key标志 :MUL
    4、把经常用来查询的字段设置为索引字段
  2、创建index
    1、创建表时
      create table 表名(...
      index(字段名),index(字段名));
    2、已有表
      create index 索引名 on 表名(字段名);
      create index name on t3(name);
    3、查看索引
      1、desc 表名; --> KEY标志为:MUL
      2、show index from 表名\G;
    4、删除索引
      drop index 索引名 on 表名;
2、唯一索引(unique)
  1、使用规则
    1、可设置多个字段
    2、约束 :字段值不允许重复,但可为 NULL
    3、KEY标志 :UNI
  2、创建
    1、创建表时创建
      unique(字段名),
      unique(字段名)
    2、已有表
      create unique index 索引名 on 表名(字段名);
    3、查看、删除 同 普通索引
3、主键索引(primary key)
    自增长属性(auto_increment,配合主键一起使用)
  1、使用规则
    1、只能有一个主键字段
    2、约束 :不允许重复,且不能为NULL
    3、KEY标志 :PRI
    4、通常设置记录编号字段id,能唯一锁定一条记录
  2、创建
   1、创建表时
    1、(id int primary key auto_increment,)auto_increment=10000;##设置自增长起始值
   2、在创建表的最后面也可以添加主键primary key(字段名)

    1、已有表添加自增长属性:
    alter table 表名 modify id int auto_increment;
    已有表重新指定起始值:
    alter table 表名 auto_increment=20000;
    2、已有表
      alter table 表名 add primary key(id);
   3、删除
    1、删除自增长属性(modify)
      alter table 表名 modify id int;
    2、删除主键索引
      alter table 表名 drop primary key;
4、外键索引(foreign key)

  1、外键(foreign key)
    1、定义 :让当前表字段的值在另一个表的范围内选择
  2、语法
    foreign key(参考字段名)
    references 主表(被参考字段名)
    on delete 级联动作
    on update 级联动作
  3、使用规则
    1、主表、从表字段数据类型要一致
    2、主表被参考字段 :主键

  4、删除外键
    alter table 表名 drop foreign key 外键名;
    外键名 :show create table 表名;
  5、级联动作
    1、cascade
      数据级联删除、更新(参考字段)
    2、restrict(默认)
      从表有相关联记录,不允许主表操作
    3、set null
      主表删除、更新,从表相关联记录字段值为NULL
  6、已有表添加外键
    alter table 表名 add
    foreign key(参考字段) references 主表(被参考字段)
    on delete ...
    on update ...

posted on 2018-09-02 11:38  zengsf  阅读(119)  评论(0编辑  收藏  举报

导航