"Cannot add or update a child row" mysql - mysql

I am continuously getting this flag:
1452 - Cannot add or update a child row: a foreign key constraint fails (mydb4653.stars, CONSTRAINT fk_stars_movie FOREIGN KEY
(movieID) REFERENCES movie (id))
when I try to insert the data into the table
These are the tables
movie(id, title, relYear, category, runTime, director,
studioName, description, rating)
actor(aID, fName, surname, gender)
stars(movieID, actorID)
movGenre(movieID, genre)
I think it could have something to do with the fact that its not the only movieID as it is the only one I am having issues with. It is definitely indexed
I have tried:
CREATE TABLE stars
(movieID INTEGER,
actorID INTEGER NOT NULL PRIMARY KEY,
CONSTRAINT fk_stars_movie FOREIGN KEY (movieID) REFERENCES movie(ID)
);
as well as manually making it the foreign key in the relation view. It is also the same data type as its primary key so that's not the issue either.
CREATE TABLE movie
(id INTEGER NOT NULL PRIMARY KEY,
title VARCHAR(100),
relYear INTEGER,
category VARCHAR(5),
runTime INTEGER,
director VARCHAR(50),
studioName VARCHAR(100),
description VARCHAR(500),
rating DECIMAL(10,2)
);

set foreign_key_checks=0;
Your insert query goes here...
set foreign_key_checks=1;

Related

Foreign Key Constraint On delete cascade not effective

I have created two tables (emp and dept). Emp contains a foreign key (deptid). I am attempting to delete a row from the dept table and am receiving a foreign key constraint error. I then altered the emp table foreign key to add constraint and delete on cascade. The code is copied here
create table dept (
deptid int primary key,
deptname varchar(20),
locid int);
create table emp (
empid int primary key,
frname varchar(15),
lname varchar(20),
hiredate datetime,
deptid int,
foreign key (deptid) references dept(deptid));
alter table emp add constraint fk_deptid foreign key (deptid)
references dept(deptid) on delete cascade;
This is the error message that I receive:
Query Error: Error: ER_ROW_IS_REFERENCED_2: Cannot delete or update a parent row: a foreign key constraint fails (test.emp, CONSTRAINT emp_ibfk_1 FOREIGN KEY (deptid) REFERENCES dept (deptid))
The problem is that you are creating two foreign key constraints for the same column. Avoid doing this, it's confusing.
The first one is created while you create the table and is unnamed. Since you didn't provide a name for it, MySQL automatically names it for you as emp_ibfk_1. This one does not have CASCADE DELETE and prevents deletion of parent keys.
The second one is on a separate SQL statement and you name it fk_deptid. This one has CASCADE DELETE and allows deletion of parent keys.
While enforcing the foreign key constraints MySQL cannot delete the row since the first constraint does not allow it. That's the error you are getting.
This is a confusing situation and I would avoid doing something like this. I would suggest having a single FK constraint for the column; specifically I would remove the first one.
For example:
create table dept (
deptid int primary key,
deptname varchar(20),
locid int);
create table emp (
empid int primary key,
frname varchar(15),
lname varchar(20),
hiredate datetime,
deptid int
-- , foreign key (deptid) references dept(deptid) -- removed
);
alter table emp add constraint fk_deptid foreign key (deptid)
references dept(deptid) on delete cascade;
insert into dept (deptid, deptname, locid)
values (1, 'Math', 123);
insert into emp (empid, frname, lname, hiredate, deptid)
values (10, 'Peter', 'Fonda', null, 1);
delete from dept where deptid = 1; -- works!

Unable to alter table with foreign key

My two empty tables:
CREATE TABLE person (
person_id SMALLINT UNSIGNED,
fname VARCHAR(20),
lname VARCHAR(20),
gender ENUM('m', 'f'),
birth_date DATE,
street VARCHAR(30),
city VARCHAR(20),
state VARCHAR(20),
country VARCHAR(20),
postal_code VARCHAR(20),
CONSTRAINT pk_person PRIMARY KEY (person_id)
);
create TABLE favorite_food (
person_id SMALLINT UNSIGNED,
food VARCHAR(20),
CONSTRAINT pk_favorite_food PRIMARY KEY (person_id, food),
CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id) REFERENCES person (person_id)
);
Needed modification:
ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;
Result:
ERROR 1833 (HY000): Cannot change column 'person_id': used in a
foreign key constraint 'fk_fav_food_person_id' of table
'tom.favorite_food'
Why is this and is there a way around this without dropping the tables and redefining them?
This is probably because there already is data in person.person_id in any rows (NOT NULL). You can circumvent this by disabling foreign key checks
I believe the best way to handle this is to drop the foreign key reference from favorite_food, alter the column in person and then recreate the foreign key reference. That will properly recreate the index on which the key depends.

Error 1215: Why is it happening?

I am confused as to why error 1215: cannot add foreign key constraint is occurring in my code. Does anybody have any ideas?
The first four tables create themselves fine, but the error is thrown when I try to create the Stars table. I am not sure what's going wrong, as the keys being referenced are primary keys and so they must be unique and non-null. Plus, those keys exist as the previous tables have been created first. It might just be a stupid mistake I made, but its better to have fresh eyes look at it, right?
This database is simplistic as it is because I'm doing it for a school assignment.
create table MovieExec
(
execName varchar(40),
certNum numeric(30, 0),
address varchar(50),
networth real,
primary key(execName),
unique key(certNum)
);
create table Stud
(
studName varchar(30),
address varchar(50),
presCNum numeric(30, 0),
primary key(studName),
foreign key (presCNum) references MovieExec(certNum)
);
create table MovieStar(
starName varchar(30),
address varchar(50),
gender varchar(1),
birthdate date,
primary key(starName)
);
create table Movies
(
movieTitle varchar(30),
movieYear numeric(4,0),
length numeric(3,0),
genre varchar(30),
studioName varchar(30),
producerCNum numeric(30, 0),
primary key (movieTitle, movieYear),
foreign key (producerCNum) references MovieExec(certNum),
foreign key (studioName) references Stud(studName)
);
create table Stars
(
movieTitle varchar(30),
movieYear numeric(4,0),
starName varchar(30),
primary key (movieTitle, movieYear, starName),
foreign key (movieTitle) references Movies(movieTitle),
foreign key (movieYear) references Movies(movieYear),
foreign key (starName) references MovieStar(starName)
);
It should be a composite foreign key for the title and the year:
foreign key (movieTitle, movieYear) references Movies(movieTitle, movieYear),
foreign key (starName) references MovieStar(starName)
It should be composite because that's the exact PK of Movies table and that's the only UNIQUE combination there currently available.
Then as #CBroe mentioned in their answer it would be a good idea to index the Stars.starName column.
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html:
“[…] in the referenced table, there must be an index where the referenced columns are listed as the first columns in the same order”
In your Movies table, you only have a primary key on the combination (movieTitle, movieYear) – but movieYear is not the first column in that key, and therefor
foreign key (movieYear) references Movies(movieYear)
in your CREATE statement for the stars table fails.
Add a key on Movies.movieYear – then creating a foreign key referencing that column on the stars table will work.
FYI: MySQL has a YEAR data type – you should use that, instead of a NUMERIC for your movie year.
And you are mixing singular and plural in your table names. Convention is to use the singular of the object that a table holds as table name; but at least you should try and be consistent with your naming scheme.

how to make a primary key a foreign key in another table?

These are my tables. I have a problem with the last one (Inscription) it doesn't accept CodeProjet as a foreign key. The error says table (Projet) doesn't have a primary key called CodeProjet but it does! I have used every trick that I know and nothing. I altered the table to add constraint, etc. Still nothing. I always get the same error. Here are the tables:
create database Gestion_Stages_Employe
create table Employe
(
NumEmploye int primary key,
NomEmploye varchar(15),
PrenomEmploye varchar(15),
SexeEmploye varchar(10),
DNaissEmploye date,
FonctionEmploye varchar(20)
)
create table TypeProjet
(
TypeProjet varchar(20) primary key,
libelleProjet varchar(20),
DureeProjet date,
)
create table Projet
(
CodeProjet int,
TypeProjet varchar(20),
DateDebut Date,
DateFin Date,
Constraint Pk_CodeProj primary key (CodeProjet,TypeProjet),
Constraint FK_TypeProj foreign key (TypeProjet) references TypeProjet(TypeProjet),
)
create table Inscription
(
NumEmploye int foreign key references Employe(NumEmploye),
CodeProjet int foreign key references Projet(CodeProjet),
dateiscription Date,
primary key (NumEmploye,CodeProjet),
)
As was mentioned in the comment, the Primary Key on the Projet table is a "composite key" (multiple columns are required to enforce uniqueness).
As a result, for your foreign key to work, you need to either remove "TypeProjet" from the primary key of Project (assuming CodeProjet is sufficient to uniquely identify a Projet), or you need to add TypeProjet to the Inscription table and define your foreign key with both columns, for example:
create table Inscription (
NumEmploye int foreign key references Employe(NumEmploye),
CodeProjet int,
dateiscription Date,
TypeProjet varchar(20),
Constraint fk_Inscription_project Foreign key (CodeProjet,TypeProjet) references Projet(CodeProjet,TypeProjet),
primary key (NumEmploye,CodeProjet),
)

Syntax error User_id not found in table help !

Sql wont let me create these table because of a syntax error can someone help me.
drop table users;
drop table intrest;
drop table friendships;
create table users(
id INT,
Fname char(15),
Lname char(15),
email char(20),
street char(15),
state char(2),
zip INT,
age INT,
gender char (2),
phone INT,
User_password char(15),
primary key (id),
foreign key (intrest_id) references intrest(id)
);
create table Intrests(
id INT,
description char(30),
Primary key (id),
foreign key (users_id) references users(id)
);
create table User_intrest(
foreign key (users_id) references users(id),
foreign key (intrest_id) references intrest(id)
);
create table friendships(
User_1_id INT,
User_2_id INT,
description Char(20),
foreign key (users_id) references users(id)
);
create table Intrests( id INT, description char(30),
Primary key (id),
foreign key (users_id) references users(id) );
create table User_intrest( foreign key (users_id) references users(id),
foreign key (intrest_id) references intrest(id) );
For interests table, where is the column users_id defined?
Column definitions for user_interest table?
You have a cyclical FK relationship:
Users has Interests(id) as a FK, and Interests has user(id) as a FK.
You don't need EITHER of these since you have a user_intrest table to link them!
You also have several typos with table names, like intrests and intrest.
Also, you should make both your User fields in Friendships be FK to Users, I'm not sure why you want a third, unrelated Users_Id field.
The first (of many) syntax errors you have is in
create table users(
...
primary key (id),
foreign key (intrest_id) references intrest(id) <--- there is no table intrest
);
I would suggest:
But STOP! Don't just copy-paste. Try yourself to see why MySQL gives you that error message: Key column 'intrest_id' doesn't exist in table, isn't the error you get?
Try to first fix that error. What do you have to do? Add an intrest_id field in table users, not just declare it as FOREIGN KEY. (It's not a useful field to have in the end, but do it anyway).
Then rerun your query and try to fix next error. One by one. If you realy get stuck somewhere, well, you know a site to ask questions :)
So, try to fix errors one by one, until you have a script that is running without any errors at all. You'll have learned much more than simply copying and pasting any answer.
CREATE TABLE Users(
id INT,
Fname char(15),
Lname char(15),
email char(50), <-- 20 is too small for emails
street char(15),
state char(2),
zip INT,
age INT,
gender char (2),
phone char(20), <-- phone should be char, not INT
user_password char(15),
PRIMARY KEY (id)
); <-- You don't really need a foreign key to Interests,
<-- that's why you have the User_interest "middle" table
CREATE TABLE Interests(
id INT,
description char(30),
PRIMARY KEY (id)
); <-- You don't really need a foreign key to Users,
<-- for the same reasons.
CREATE TABLE User_interest(
user_id INT, <-- These foreign keys are
interest_id INT, <-- good, but you need to
<-- declare them as fields, too
PRIMARY KEY (user_id, interest_id), <-- It's good if all tables have PK
FOREIGN KEY (user_id) REFERENCES Users(id),
FOREIGN KEY (interest_id) REFERENCES Interests(id)
);
CREATE TABLE Friendships(
user_1_id INT,
user_2_id INT,
description char(20),
PRIMARY KEY (user_1_id, user_2_id),
FOREIGN KEY (user_1_id) REFERENCES Users(id),
FOREIGN KEY (user_2_id) REFERENCES Users(id)
);