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

邮差的信 提交于 2019-12-07 19:05:51

问题


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

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