如何在父 table(Tb2) 的子 table(Tb1) 中插入数据,该子 table(Tb1) 也是 MySQL 中子(Tb1)的父(Tb2)?
How to insert data in child table(Tb1) of parent table(Tb2) that is also the parent(Tb2) of child(Tb1) in MySQL?
我是 MySQL 的新手,几天前才开始使用它。对于我的家庭作业,为了简单起见,MySQL 将其默认设置为 MyISAM,并让我创建了一个医院示例数据库用于在 MySQL.
上进行练习
但为了我个人的目的和一些研究表明 InnoDB 与 MyISAM 相比实际上强制执行 FK,我将默认设置切换为 InnoDB 并尝试重新创建我在作业中使用 MyISAM 所做的相同数据库。
然后问题像卡车一样重创了我,我的 "ward" table 如下:
create table Ward
(Code varchar(1) primary key not null,
Name varchar(15) not null,
Consultant varchar(3) not null);
alter table ward
add foreign key (Consultant)
references Doctor(ID);
我的医生 table 是这样说的:
create table Doctor
(ID varchar(3) primary key not null,
Name varchar(15) not null,
Ward varchar(1) not null);
alter table doctor
add foreign key (Ward)
references Ward(Code);
之后,我尝试在 table 中的任何一个中输入数据,当我尝试将数据输入 "ward" table 和 "doctor" table 分别为:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key
constraint fails (hospital
.ward
, CONSTRAINT ward_ibfk_1
FOREIGN
KEY (Consultant
) REFERENCES doctor
(ID
))
ERROR 1452 (23000): Cannot add or update a child row: a foreign key
constraint fails (hospital
.doctor
, CONSTRAINT doctor_ibfk_1
FOREIGN KEY (Ward
) REFERENCES ward
(Code
))
如何将数据输入 table 中的任一个?
谢谢,抱歉给您带来麻烦!
大概'wrong'这样来来回回的FK
您可以在创建表时禁用外键。但是你可能会遇到插入问题——一个插入会发现 FK 违规,因为你还没有完成另一个。
如果您的 FK 中没有循环,则只需按 'right' 顺序创建表。
我是 MySQL 的新手,几天前才开始使用它。对于我的家庭作业,为了简单起见,MySQL 将其默认设置为 MyISAM,并让我创建了一个医院示例数据库用于在 MySQL.
上进行练习但为了我个人的目的和一些研究表明 InnoDB 与 MyISAM 相比实际上强制执行 FK,我将默认设置切换为 InnoDB 并尝试重新创建我在作业中使用 MyISAM 所做的相同数据库。
然后问题像卡车一样重创了我,我的 "ward" table 如下:
create table Ward
(Code varchar(1) primary key not null,
Name varchar(15) not null,
Consultant varchar(3) not null);
alter table ward
add foreign key (Consultant)
references Doctor(ID);
我的医生 table 是这样说的:
create table Doctor
(ID varchar(3) primary key not null,
Name varchar(15) not null,
Ward varchar(1) not null);
alter table doctor
add foreign key (Ward)
references Ward(Code);
之后,我尝试在 table 中的任何一个中输入数据,当我尝试将数据输入 "ward" table 和 "doctor" table 分别为:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (
hospital
.ward
, CONSTRAINTward_ibfk_1
FOREIGN KEY (Consultant
) REFERENCESdoctor
(ID
))ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (
hospital
.doctor
, CONSTRAINTdoctor_ibfk_1
FOREIGN KEY (Ward
) REFERENCESward
(Code
))
如何将数据输入 table 中的任一个?
谢谢,抱歉给您带来麻烦!
大概'wrong'这样来来回回的FK
您可以在创建表时禁用外键。但是你可能会遇到插入问题——一个插入会发现 FK 违规,因为你还没有完成另一个。
如果您的 FK 中没有循环,则只需按 'right' 顺序创建表。