How do I create a table with a two primary keys of two foreign keys?

心不动则不痛 提交于 2019-12-06 06:18:57

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

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:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!