[英]Can't add foreign key constraint, (#1215 - Cannot add foreign key constraint)
我正在嘗試創建一個數據庫,我的數據庫中有一個表,想添加另一個表。
我的桌子:
create table department(
dept_name varchar(20),
building varchar(20) not null,
budget numeric(8,2),
primary key (dept_name)
)
我想添加此表:
create table student (
ID varchar(5),
name varchar(20) not null,
dept_name varchar(20),
tot_cred numeric(3,0),
primary key (ID),
foreign key (dept_name) references department
)
但是我得到這個錯誤:
#1215 - Cannot add foreign key constraint
你們能幫我解決這個問題嗎? 謝謝。
您的第二張桌子應該是-
create table student (
ID varchar(5),
name varchar(20) not null,
dept_name varchar(20),
tot_cred numeric(3,0),
primary key (ID),
foreign key (dept_name) references department(dept_name)
)
注意:最好將dept_id作為int包含在父表中,並在第二個表中創建引用以獲取更好的性能。
按照以下方式創建表-
create table department(
dept_id int auto_increment,
dept_name varchar(20),
building varchar(20) not null,
budget numeric(8,2),
primary key (dept_id)
);
create table student (
ID varchar(5),
name varchar(20) not null,
dept_it int,
tot_cred numeric(3,0),
primary key (ID),
foreign key (dept_id) references department(dept_id)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.