mysql的索引与键值
索引类型
类型 | 含义 |
---|---|
index | 普通索引 |
Unique | 唯一索引 |
Fulltext | 全文索引(性能差,不常用) |
Primary key | 主键(拥有唯一索引的全部特征) |
Foreign key | 外键 |
主键与唯一索引的区别
- 主键更倾向于一种约束,唯一索引更倾向于一个条件
- 在一个表里面,主键只能有一个,而唯一索引可以有多个
- 主键具有唯一索引的特性,具有唯一特性的字段不一定是唯一索引
index 普通索引
使用说明
- 一个表中可以有多个index字段
- 字段值允许重复,且可以赋空值
- 把查询频率高的字段设置为index字段
- 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
注意事项:
- 一个表中只能有一个主键
- 对应的字段值不允许重复,且不允许为null
- 主键字段的key标志是PRI
- primary key通常与aoto_increment连用
- 当需要删除primary key时,需要先删除auto increment
- 经常把表中能够唯一标识记录的字段设置为主键字段,如id字段
- 主键不要与业务相关
创建主键
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,太离谱了