0

Not sure why getting this error

CREATE TABLE Works(
SSN int,
ProjName varchar(255),
ProjNum int,
DeptNum int,
PRIMARY KEY (SSN,ProjName,ProjNum),
FOREIGN KEY (SSN) REFERENCES Employee(SSN),
FOREIGN KEY (DeptNum) REFERENCES Department(DeptNum)
);

CREATE TABLE Project(
ProjName varchar(255),
ProjNum int,
ProjDesc varchar(255),
PRIMARY KEY (ProjName,ProjNum),
FOREIGN KEY (ProjName) REFERENCES Works(ProjName),
FOREIGN KEY (ProjNum) REFERENCES Works(ProjNum)
);

Error

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'project_ibfk_1' in the referenced table 'Works'

select * from Employee where Address = 'new york'
in (select * from Employee where DOB= '01012012');

select * from Employee where Address = 'new york'
not in (select * from Employee where DOB= '010120120');

Error Code: 1241. Operand should contain 1 column(s)

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828

2 Answers2

0

When you create a foreign key, you must match all the columns of the primary key in the table you reference. If the referenced table has two columns in its primary key, your foreign key must have two columns.

Creating a separate foreign key for each column is not the same.

You might also like to read this checklist for foreign keys: https://stackoverflow.com/a/4673775/20860

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
0

you might try following statement.

CREATE TABLE Works(
SSN int,
ProjName varchar(255),
ProjNum int,
DeptNum int,
PRIMARY KEY (SSN,ProjName,ProjNum),
FOREIGN KEY (SSN) REFERENCES Employee(SSN),
FOREIGN KEY (DeptNum) REFERENCES Department(DeptNum)
);

CREATE TABLE Project(
ProjName varchar(255),
ProjNum int,
ProjDesc varchar(255),
PRIMARY KEY (ProjName,ProjNum),
FOREIGN KEY (ProjNum, ProjName) REFERENCES Works(ProjNum, ProjName)
);

just change:

FOREIGN KEY (ProjName) REFERENCES Works(ProjName),
FOREIGN KEY (ProjNum) REFERENCES Works(ProjNum)

to

FOREIGN KEY (ProjNum, ProjName) REFERENCES Works(ProjNum, ProjName)
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
xiaojueguan
  • 870
  • 10
  • 19