问题
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 complains there is a problem with syntax?
Desired Result: have Table 'Machine-Part' use 'Machine_ID' & 'Part_ID' as both primary keys (which are both foreign keys).
回答1:
If you declare the constraint separately (table level), it makes more sense
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)
)
Link tables almost always need a reverse index too
回答2:
Something like this -
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;
You can find all information on these pages:
- FOREIGN KEY Constraints
- CREATE TABLE Syntax
来源:https://stackoverflow.com/questions/9114274/how-do-i-create-a-table-with-a-two-primary-keys-of-two-foreign-keys