I created both tables with no problem. I sucessfully put the values in the emplo
ID: 3588996 • Letter: I
Question
I created both tables with no problem. I sucessfully put the values in the employees table is correct. However, does anybody know why i cannot process my values for the emp_num for the titles table. I set the emp_num column in the titles table as a foreign key and when try to insert the values into it , it say this
#1452 - Cannot add or update a child row: a foreign key constraint fails (`cis202920_13`.`titles`, CONSTRAINT `FK_titles` FOREIGN KEY (`emp_no`) REFERENCES `employees` (`emp_no`)) .
Here is my coding for the setting emp_no as a foreign key in the titles table and below it is what should be in each table. What am i doing wrong??
ALTER TABLE titles ADD CONSTRAINT FK_titles
FOREIGN KEY (emp_no) REFERENCES employees (emp_no);
employees table
titles table
Column name
Type
Details
emp_no
int
Primary key
birth_date
date
first_name
Varchar 14
last_name
Varchar 16
hire_date
date
Column name
Type
Details
emp_no
int
Foreign-key (with employees table)
Primary key
title
Varchar 50
Primary key
from_date
date
Primary key
to_date
date
employees table
titles table
Column name
Type
Details
emp_no
int
Primary key
birth_date
date
first_name
Varchar 14
last_name
Varchar 16
hire_date
date
Column name
Type
Details
emp_no
int
Foreign-key (with employees table)
Primary key
title
Varchar 50
Primary key
from_date
date
Primary key
to_date
date
Explanation / Answer
Explanation:
A foregin key is a reference to the unique value of primary key in the base table (i.e. employees)
You can't add/modify a foregin key on emp_no because it should be created first in the base table.
Even you can't modify a primary key in the base table.
So here you are trying to create a new record in the titles table with new foreign key value not present in the base table and the titles table refers its emp_no to a unique value in the employees table.
That is why your insert statement is failing.
Hence,first you insert a record for that emp_no in the base table.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.