I tried to insert data into the table Bookratings, but I keep getting this error message. Is this because when I try to insert, it creates duplicates in the Bookratings table, which is not allowed by the PRIMARY key constraint?
MySQL Error 1452 - Cannot add or update a child row: a foreign key constraint fails
My actual code:
drop database if exists amazon2;
create database if not exists amazon2;
use amazon2;
create table books(
ISBN varchar(13),
Title varchar(255),
Author varchar(255),
Year int(10),
Puplisher varchar(255),
ImageURL varchar(255),
Genre varchar(12),
unitprice decimal(6,2),
primary key (ISBN)
);
create table users(
UserID int(11),
Country varchar(250),
Age int(11),
primary key (UserID)
);
create table bookratings(
UserID int(11) not null,
ISBN varchar(13) not null,
Rating int(11),
primary key (UserID, ISBN),
foreign key (ISBN) references books (ISBN) on delete cascade on update cascade,
foreign key (UserID) references users (UserID) on delete cascade on update cascade
);
create table orders(
OrderID int(11),
UserID int(11) not null,
Year int(10),
totalpay decimal(6,2),
primary key (OrderID),
foreign key (UserID) references users (UserID)
);
create table trans(
OrderID int(11) not null,
ISBN varchar(13) not null,
Quantity int(11),
primary key (OrderID, ISBN),
foreign key (OrderID) references orders (OrderID),
foreign key (ISBN) references books (ISBN)
);
I have to clarify something: Given by the task, I am not allowed to add any other attributes or delete the existing attributes.
Foreign key constraint violation means the table you're trying to update contains references to some other table, and you're somehow breaking that reference.
If I've got a table Movies
+----------+---------------+
| Movie_ID | Movie_Name |
+----------+---------------+
| 1 | Jaws |
| 2 | Star-Wars |
| 3 | Jurassic Park |
+----------+---------------+
And a table User_Reviews
+---------+----------+-------+
| User_ID | Movie_ID | Score |
+---------+----------+-------+
| 1 | 1 | 2.5 |
| 2 | 1 | 5 |
| 3 | 2 | 4 |
| 4 | 2 | 3 |
| 5 | 2 | 4.5 |
| 6 | 3 | 5 |
+---------+----------+-------+
In the User_Reviews table, Movie_ID is a foreign key.
I can't have a review with Movie_ID = 10, because that movie doesn't exist in the Movies table. If I did try to do that, I'd get a foreign key constraint error.
Related
I need some help, I am trying to create a recursive relation using the code below, but keep getting an error
CREATE TABLE `Employee` (
`SSN` int,
`address` varchar(50),
`salary` varchar(50),
`sex` varchar(50),
`birthDate` varchar(50),
`dependantId` int,
`supervisorId` int,
PRIMARY KEY (`SSN`),
FOREIGN KEY (`dependantId`) REFERENCES `Dependant`(`dependantId`),
FOREIGN KEY (`supervisorId`) REFERENCES `Employee`(`supervisorId`)
);
This is the error I'm getting:
#1005 - Can't create table company recursive.employee (errno: 150 "Foreign key constraint is incorrectly formed")
The table needs an ID column to be "referenceable" by foreign key constraints. That column musst be UNIQUE and ideally NOT NULL as well. A typical solution would look like:
CREATE TABLE Employee (
`SSN` int,
`address` varchar(50),
`salary` varchar(50),
`sex` varchar(50),
`birthDate` varchar(50),
id int not null unique, -- non nullable unique (acts as a key)
dependantId int, -- nullable reference
supervisorId int, -- nullable reference
PRIMARY KEY (`SSN`),
FOREIGN KEY (dependantId) REFERENCES Employee (id),
FOREIGN KEY (supervisorId) REFERENCES Employee (id)
);
In this case dependantId and supervisorId can be null and become references that point to the same table Employee.
As a side note, typically hierarchies only include references to the supervisor and not to the dependant. In your case the latter is somewhat redundant and won't work well if a supervisor has more than one dependant.
the reference should go to the SSN as it is the primary key
So you would get
CREATE TABLE `Employee` (
`SSN` int,
`address` varchar(50),
`salary` varchar(50),
`sex` varchar(50),
`birthDate` varchar(50),
`dependantId` int,
`supervisorId` int,
PRIMARY KEY (`SSN`),
FOREIGN KEY (`dependantId`) REFERENCES `Employee`(`SSN`),
FOREIGN KEY (`supervisorId`) REFERENCES `Employee`(`SSN`)
);
INSERT INTO Employee VALUES (1,'adreess1','10', 'male', '2000-01-01',NULL,NULL)
INSERT INTO Employee VALUES (2,'adreess1','10', 'male', '2000-01-01',NULL,1)
INSERT INTO Employee VALUES (3,'adreess1','10', 'male', '2000-01-01',2,1)
SELECT * FROM Employee
SSN | address | salary | sex | birthDate | dependantId | supervisorId
--: | :------- | :----- | :--- | :--------- | ----------: | -----------:
1 | adreess1 | 10 | male | 2000-01-01 | null | null
2 | adreess1 | 10 | male | 2000-01-01 | null | 1
3 | adreess1 | 10 | male | 2000-01-01 | 2 | 1
db<>fiddle here
I have two tables, with foreign keys, but when delete a record from 'fb_campaign' get follow error:
#1451 - Cannot delete or update a parent row: a foreign key constraint fails (mydb.fb_campaign_cat, CONSTRAINT fb_campaign_cat_ibfk_1 FOREIGN KEY (id) REFERENCES fb_campaign (id_cat))
Issue occurs when I add the second foreign key.
table1: fb_campaign_cat
+----+-----------+
| id | fb_cat |
+----+-----------+
| 1 | category1 |
| 2 | category2 |
| 3 | category3 |
+----+-----------+
table2: fb_campaign
+-------+--------+-----------+
| id_fb | id_cat | name |
+-------+--------+-----------+
| 1 | 1 | campaign1 |
| 2 | 2 | campaign2 |
+-------+--------+-----------+
** schema **
CREATE TABLE `fb_campaign_cat` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fb_cat` varchar(30) CHARACTER SET utf8mb4 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `fb_campaign` (
`id_fb` int(11) NOT NULL AUTO_INCREMENT,
`id_cat` int(11) NOT NULL,
`name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
FOREIGN KEY
ALTER TABLE fb_campaign
ADD CONSTRAINT fb_campaign_cat
FOREIGN KEY (id_cat)
REFERENCES fb_campaign_cat(id)
ON DELETE CASCADE;
ALTER TABLE fb_campaign_cat
ADD FOREIGN KEY (id) REFERENCES fb_campaign(id_cat);
The simple way would be to disable the foreign key check; make the changes then re-enable foreign key check.
SET FOREIGN_KEY_CHECKS=0; -- to disable them
SET FOREIGN_KEY_CHECKS=1; -- to re-enable them
I have created two tables
EMPLOYEE
CREATE TABLE employee (
emp_id INT AUTO_INCREMENT NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(20) NOT NULL,
address VARCHAR(20) NOT NULL,
PRIMARY KEY (emp_id)
);
TEAM
CREATE TABLE team (
team_id INT AUTO_INCREMENT NOT NULL,
name VARCHAR(20),
manager_id INT (20),
PRIMARY KEY (team_id)
);
I am trying to add a add a foreign key:
ALTER TABLE employee ADD FOREIGN KEY (manager_id) REFERENCES team(manager_id);
It is giving me an error telling me that the column does not exist
ERROR 1072 (42000): Key column 'manager_id' doesn't exist in table
But it does show when I Describe team
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+----------------+
| team_id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
| manager_id | int(20) | YES | | NULL | |
+------------+-------------+------+-----+---------+----------------+
Column manager_id does not exists in table employee.
Something like this would be more meaningful:
ALTER TABLE team ADD FOREIGN KEY (manager_id) REFERENCES employee(emp_id);
Possibly, you also build a table to represent the relationship between employees and teams. As of now, nothing in your schema can be used to relate an employee to one or several teams.
I am trying to set up a MySQL database where a column is a foreign key pointing to another table that auto increments. When I try to create the table with the foreign key, I get the following error:
Can't create table '{DATABASE}' . '{TABLE}' (errorno: 150 "Foreign key constraint is incorrectly formed")
An answer found here says that the problem could be that I am trying to set a normal int as a foreign key pointing to an autoincrement int. How should I go about setting up my table structure?
Here is the statement that produces the error:
create table test_scores(id INT NOT NULL AUTO_INCREMENT,
student_id INT,
FOREIGN KEY (id) REFERENCES students(student_id) ON DELETE CASCADE,
test_id INT NOT NULL,
FOREIGN KEY (test_id) REFERENCES tests(id) ON DELETE CASCADE,
score INT NOT NULL,
PRIMARY KEY (id));
Parent tables:
students
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
tests
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
On this line:
FOREIGN KEY (id) REFERENCES students(student_id) ON DELETE CASCADE,
you probably meant to do this:
FOREIGN KEY (student_id) REFERENCES students(id) ON DELETE CASCADE,
Otherwise you're trying to make id the foreign key, which isn't going to work because you can't know what id is even going to be until you insert a record. Additionally, students has no student_id column, so the attempt to use it as the relationship for the foreign key would fail.
I have a table which looks like this:
mysql> SHOW COLUMNS FROM Users;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| user_id | int(10) | NO | PRI | NULL | auto_increment |
| username | varchar(50) | YES | | NULL | |
| password | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
| phone | varchar(255) | YES | | NULL | |
I am trying to create a new table like this:
create table jobs (id int, FOREIGN KEY (user_id) REFERENCES Users(user_id)) ENGINE=INNODB;
But I am getting this error:
ERROR 1072 (42000): Key column 'user_id' doesn't exist in table
I am sure I am missing something very basic.
Try this:
create table jobs (
id int,
user_id int,
FOREIGN KEY (user_id) REFERENCES Users(user_id)
) ENGINE=INNODB;
The first user_id in foreign key constraint refers to the table where the contraint is defined and the second refers to the table where it is pointing to.
So you need a field user_id in your jobs table, too.
This is the script you need:
CREATE TABLE jobs
(
id int NOT NULL,
user_id int NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES Users(user_id)
)
Here's a good reference to learn the basics about setting up relationships: SQL FOREIGN KEY Constraint
You're trying to define as FOREIGN KEY, a column which is not present on your query.
That's the reason why you are receiving Key column 'user_id' doesn't exist in table
Observe your query:
create table jobs (
id int,
FOREIGN KEY (user_id) REFERENCES Users(user_id)
) ENGINE=INNODB;
As the other answers have demonstrated:
you have to define the creation of the column of your new table, which will be a FK for a PK from another table
create table jobs (
id int,
user_id int NOT NULL
FOREIGN KEY (user_id) REFERENCES Users(user_id)
) ENGINE=INNODB;
Create table attendance:
CREATE TABLE tbl_attendance
(
attendence_id INT(100) NOT NULL,
presence varchar(100) NOT NULL,
reason_id varchar(100) NULL,
PRIMARY KEY (attendance_id)
);