mysql的索引与键值 8月1日学习笔记

mysql的索引与键值

索引类型

类型含义
index普通索引
Unique唯一索引
Fulltext全文索引(性能差,不常用)
Primary key主键(拥有唯一索引的全部特征)
Foreign key外键

主键与唯一索引的区别

  1. 主键更倾向于一种约束,唯一索引更倾向于一个条件
  2. 在一个表里面,主键只能有一个,而唯一索引可以有多个
  3. 主键具有唯一索引的特性,具有唯一特性的字段不一定是唯一索引

index 普通索引

使用说明

  1. 一个表中可以有多个index字段
  2. 字段值允许重复,且可以赋空值
  3. 把查询频率高的字段设置为index字段
  4. Index字段的key编制是MUL

创建表时添加索引

 create table index_t( name varchar(255) not null , age tinyint unsigned not null, index(name), index(age));

直接添加索引

create  index age_index on index_t(age);

查看当前索引

show index from index_t;

如图
在这里插入图片描述删除索引

drop index age on index_t;

注: 没有索引名字,可以写字段名字(如果不指定索引名字,索引名字默认跟字段名字相同)

主键 primary key

注意事项:

  1. 一个表中只能有一个主键
  2. 对应的字段值不允许重复,且不允许为null
  3. 主键字段的key标志是PRI
  4. primary key通常与aoto_increment连用
  5. 当需要删除primary key时,需要先删除auto increment
  6. 经常把表中能够唯一标识记录的字段设置为主键字段,如id字段
  7. 主键不要与业务相关

创建主键

drop table if exists test;
create table test (id int auto_increment,name varchar(10),age int ,primary key(id),index(name));

添加主键

 alter table test add id int primary key auto_increment first;

外键 foreign key

foreign key 表A (字段名) references 表B (字段名)
on uodate cascade
on delete cascade

创建两张表

mysql>  create table dept(id int auto_increment,deptno int(5) not null,deptname varchar(255),primary key (id));
Query OK, 0 rows affected (0.39 sec)


mysql> create table staff(id int auto_increment ,dept int(5),name varchar(25),primary key(id),foreign key (dept) references dept(id) on update cascade on delete cascade);
Query OK, 0 rows affected (0.53 sec)

注意

1,两张表里要设主键和外键的字段的数据类型或者数据长度不一样 (例如这个是int 另外一个是tinyint,或者都是int,但是设置的长度不同)
2,某个表里已经有记录了
3、两个表的引擎不一样,查看表的引擎语句:
show table status from 数据库名 where name=‘表名’;
4、要设置外键的字段不能为主键
5、改建所参考的字段必须为主键
6、两个字段必须具有相同的数据类型和约束

唯一索引 unique

create table chen(id int auto_increment primary key ,name char(5) not null,title char(255) not null , unique index(title));

还有一个全文索引,用的比较少不写了
今天一天到这里就结束了就学习了一个两小时的mysql,太离谱了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈小c

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值