转载部分

MySQL-约束与索引

2019-06-03  本文已影响2人  遇明不散

约束

保证数据的完整性、一致性、有效性

默认约束
非空约束

索引

定义

对数据库中表的一列或者多列的值进行排序的一种结构(MySQL中用Btree方式)

优缺点
索引示例
# 开启运行时间检测
set profiling=1;
# 执行查询语句
select name from t1 where name="lucy99999";
# 查看执行时间
show profiles;
# 在name字段创建索引
create index name on t1(name);
# 再执行查询语句
select name from t1 where name="lucy88888";
# 查看执行时间
show profiles;
索引分类
普通索引 index
# 创建index
# 创建表时
create table 表名(...,index(字段名),index(字段名),...);
# 已有表
create index 索引名 on 表名(字段名);

# 查看索引
desc 表名
show index from 表名\G;

# 删除索引
drop index 索引名 on 表名;
唯一索引 unique key
# 创建唯一索引
# 创建表时创建
create table 表名(...,unique(字段名),unique(字段名),...);
# 在已有表中创建
create unique index 索引名 on 表名(字段名);
# 删除唯一索引
drop index 索引名 on 表名;
# index,unique在删除时只能一个一个删
主键索引 primary key
# 创建主键索引
# 创建表时
create table 表名(字段名 数据类型 primary key [auto_increment],...)
auto_increment = 起始值;
# 已有表
alter table 表名 add primary key(字段名);
# 删除自增长属性(modify)
alter table 表名 modify 字段名 数据类型;
# 删除主键索引
alter table 表名 drop primary key;
# 已有表添加自增长属性
alter table 表名 modify 字段名 数据类型 auto_increment;
# 已有表重新指定起始值
alter table 表名 auto_increment = 起始值;
外键索引 foreign key
# 创建外键
foreign key(参考字段名)
references 主表(被参考字段名)
on delete 级联动作
on update 级联动作

# 在已有表中添加外键
# 在已有表中添加外键时,会受到表中原有数据的限制
alter table 表名 add
foreign key(参考字段名) references 被参考表名(被参考字段名)
on delete 级联动作
on undate 级联动作

# 查看外键名
show create table 表名;
# 删除外键
alter table 表名 drop foreign key 外键名;

级联动作

上一篇 下一篇

猜你喜欢

热点阅读