项目场景:
通过sql语言在MySQL查询中建立表,其中一个表引用其他表的属性出现问题报错1822
问题描述
被引用的表——用户信息表:
可以看到其中已有主键s_id,为自增长形式
CREATE TABLE 用户信息表
(
s_id int unsigned AUTO_INCREMENT not null PRIMARY KEY,
s_no varChar(9) unique not null,
s_name varchar(10) not null,
s_createAt timestamp not null default current_timestamp,
s_updateAt timestamp not null default current_timestamp on update current_timestamp
);
引用用户信息的表——耗材借出表:
create table 耗材借出表
(
loan_id int unsigned AUTO_INCREMENT not null PRIMARY KEY,
c_no varchar(50)not null ,
loan_num int check(loan_num>0) not null,
loan_give_person varchar(9) not null default '用户已注销',
loan_take_person varchar(9) not null default '用户已注销',
loan_createAt timestamp not null default current_timestamp,
loan_updateAt timestamp not null default current_timestamp on update current_timestamp,
foreign key(c_no) references 耗材库存信息表(c_no) on delete cascade on update cascade,
foreign key(loan_give_person,loan_take_person) references 用户信息表(s_no,s_no) on delete set default on update cascade
);
主要语句如下:外键设置了删除和更新级联
foreign key(loan_give_person,loan_take_person) references 用户信息表(s_no,s_no) on delete set default on update cascade
原因分析:
经过修改发现是由于借出人和接收人都需要的是用户信息表中的用户编号s_no,所以两者都引用了用户信息表中的s_no出现报错,将两个外键引用分开即可
解决方案:
将最后一行的外键引用分成两行写:
foreign key(loan_give_person) references 用户信息表(s_no) on delete set default on update cascade,
foreign key(loan_take_person) references 用户信息表(s_no) on delete set default on update cascade
可以成功建立数据库
感谢观看~希望对你有帮助