关于数据库mul键的疑惑

关于数据库mul键的疑惑

注意看,这个男人叫小帅,今天在上课的时候,他看到了小美。一时间,他竟然走神了,因此给自己留下了一个课下的功课!!!

建了两张表,一张叫employee,另外一张叫department,前者的dept_id字段是后者id字段的外键

使用了以下语句,建立好这两张表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
create database mydb1

use mydb1

create table department(
id int primary key auto_increment comment '部门号',
dname varchar(30) not null comment '部门名称'
)comment '部门';

create table employee(
id int primary key auto_increment comment '员工号',
name varchar(45) not null comment '员工名称',
dept_id int not null comment '部门号',
constraint fk foreign key (dept_id) references department(id) on delete restrict on update cascade
) comment '员工表';

插入一些数据

1
2
3
4
5
insert into department values (1,'开发部'),(2,'创新部');

insert into employee values (1,'张三',1),(2,'李四',1);

insert into employee values (3,'王五',2);

查看以下机构吧那就

1
desc employee

image-20241119162733407

1
show create table employee

image-20241119162814631

这可太完美啦,好!怎么删除外键约束呢

看上一张图,constraint后面紧跟的字符,是fk

1
alter table employee drop foreign key fk

image-20241119163109745

确实没有了constraint那一行,但是desc employee

结果依旧是

image-20241119162733407

为什么还有mul,开启网络冲浪模式

是因为dept_id字段还有索引存在,删除即可,但是索引名叫什么呢?

哇哇哇!!!你太聪明了,就是前面那个叫fk的家伙

1
alter table employee drop index fk

image-20241119163619664

也可以通过以下语句查看索引名称

1
show indexes from employee

Key_name那一列对应的就是索引名称,其实我觉得这样说并不是很准确,但可以通过这个方法找,后面有更深的理解再更新

期间遇到另外一个问题

1452 - Cannot add or update a child row: a foreign key constraint fails (mydb1.#sql-1a24_8, CONSTRAINT fk FOREIGN KEY (dept_id) REFERENCES department (id) ON DELETE RESTRICT ON UPDATE CASCADE)

说了很长,意思就是,你创建外键的这个字段在employee里必须要存在,而且里面填的数据必须要在department里的id字段里能找到对应的,一开始我的dept_id全是0,就报了这个错误,后面修改了字段数据,但是id字段里的数据是1和8这两个部门号,我在employee里填的是1和2,所以还是出错了。需要注意这个问题!!!

后续添加字段的语句

1
2
3
alter table employee add dept_id int not null;

alter table employee add constraint fk foreign key(dept_id) references department(id) on delete restrict on update cascade;

mul键

在数据库中,”mul”属性通常指的是一个索引包含多个列,即多列索引或多重索引。