Mysql-----约束、索引

约束

作用:保证数据的完整性,一致性,有效性,

约束分类:

            1)默认约束(default):插入记录时,如果不给该字段,则使用默认值

            2)非空约束(not NULL): 不允许该字段的值由NULL记录

示例:

sex enum("M","F","S") not null defalut "S"

MySQL索引:

定义:对数据库的表的一列或多列的值进行排序(Btree方式)的一种结构

优点:加快数据检索的速度

缺点:

  • 索引需要占领物理存储空间
  • 对表中数据进行增加、删除和修改的时候,索引需要动态维护,降低了数据的维护速度
    1)开启运行时间检测: set profiling=1;
    2)执行查询语句 :
    select name from t1 where name="lucy99999";
    3)查看执行时间
    show profiles;
    4)在name字段创建索引
    craete index name on t1(name);
    5)再执行查询语句
    select name from t1 where name="lucy88888";
    6)查看执行时间
    show profiles;
    7)关闭运行时间检测:
    set profiling=0;

索引的类型:

1.普通索引(index)

1)使用规则:

  • 可以设置多个字段
  • 字段值无约束
  • key标志:MUL

2)创建index

  1.       创建表时创建:create table 表名(... index(字段名),index(字段名));
  2.       已有表中创建:create index 索引名 on 表名(字段名);
  3.       查看索引:desc 表名 ------->key标志:MUL          (show index from 表名)
  4.       删除索引:drop index 索引名 on 表名

2.唯一索引(unique index)

1)使用规则:

  • 可以设置多个字段
  • 约束:字段值不允许重复,但可以为NULL
  • key标志:UNI

2)创建唯一约束unique index

  1. 创建表时创建:unique index(字段名),unique index(字段名)
  2. 已有表中创建:create unique index 索引名 on 表名(字段名)

3)查看索引    desc 表名 ---->key标志:NUI

4)删除索引     drop unique index 索引名 on 表名

3.主键约束(primary key)

自增长属性 auto_increment,配合主键一起使用)

使用规则:

  • 一个表中只能有一个primary key字段
  • 约束:不允许重复,并且不能为NULL
  • key标志:PRI
  • 通常设置记录编号字段id,能唯一所锁定一条记录

创建主键:[通常将id设置为主键]

  • 创建表时创建:(id int primary key auto_increment)auto_increate=起始值;
  • 已有表中重新指定起始值:alter table 表名 auto_increment=起始值;
  • 已有表创建主键:alter table 表名 add primary key(id);

删除:

  • 删除自增长属性(modify):alter table 表名 modify id int;
  • 删除主键索引:alter table 表名 drop primary key;

4.外籍索引(foreign key)

定义:让当前表字段的值在另一个表的范围内进行选择

语法:

        foreign key(参考字段名)

        references 主表 (被参考字段名)

        on delete (级联动作)

        on update (级联动作)

级联动作:
              1)cascade
                 数据级联删除、更新(参考字段)
              2)restrict (默认)
                  从表有相关联记录,不允许主表操作
              3) set null
                  主表删除、更新,从表相关联记录字段值为null

删除外键:   alter table 表名 drop foreign key 外键名;
找外键名 :   show create table 表名
已有表添加外键:
               alter table 表名 add
               foreign key(参考字段) references 主表(被参考字段)
               on delete ...
               on update ...


使用规则:
       1.主表、从表字段数据类型要一致
        2.主表被参考字段 :主键

猜你喜欢

转载自blog.csdn.net/py_1995/article/details/84310732