create table Machine
(
Machine_ID int primary key,
Machine_Name varchar(30)
Machine_Title varchar(30)
)
create table Part
(
Part_ID int primary key,
Part_Name varchar(30),
Part_Description varchar(30)
)
//How do I make this table below?
create table Machine-Part
(
Machine_ID int foreign key references (Machine.Machine_ID),
Part_ID int foreign key references (Part.Part_ID)
Factory_Note varchar(30);
)
Mysql抱怨语法有问题?
所需结果:让表'Machine-Part'使用'Machine_ID'& 'Part_ID'作为两个主键(都是外键)。
答案 0 :(得分:7)
如果单独声明约束(表级别),则更有意义
create table Machine-Part
(
Machine_ID int NOT NULL ,
Part_ID int NOT NULL ,
Factory_Note varchar(30) NULL,
PRIMARY KEY (Machine_ID, Part_ID),
UNIQUE INDEX (Part_ID, Machine_ID),
foreign key (Machine_ID) references (Machine.Machine_ID),
foreign key (Part_ID) references (Part.Part_ID)
)
链接表几乎总是需要反向索引
答案 1 :(得分:2)
像这样 -
CREATE TABLE Machine(
Machine_ID INT PRIMARY KEY,
Machine_Name VARCHAR(30),
Machine_Title VARCHAR(30)
)
ENGINE = INNODB;
CREATE TABLE Part(
Part_ID INT PRIMARY KEY,
Part_Name VARCHAR(30),
Part_Description VARCHAR(30)
)
ENGINE = INNODB;
create table `Machine-Part`(
Machine_ID int,
Part_ID int,
Factory_Note varchar(30),
CONSTRAINT fk_Machine_ID FOREIGN KEY (Machine_ID) REFERENCES Machine(Machine_ID),
CONSTRAINT fk_Part_ID FOREIGN KEY (Part_ID) REFERENCES Part(Part_ID)
)
ENGINE = INNODB;
您可以在这些页面上找到所有信息: