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
Related
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 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.
I am using the below create table to create a posts table in mysql :
mysql> create table posts(
-> post_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> author_id INT NOT NULL,
-> title varchar(50),
-> post TEXT,
-> data DATE,
-> FOREIGN KEY (author_id)
-> REFERENCES authors(author_id)
-> ON DELETE RESTRICT)ENGINE=INNODB;
But i always get this error:
ERROR 1005 (HY000): Can't create table 'myFirstBlog.posts' (errno: 150)
The describe of my authors table is as follows:
mysql> desc authors;
+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| author_id | int(11) | NO | PRI | NULL | auto_increment |
| user_name | varchar(16) | YES | | NULL | |
| password | varchar(40) | YES | | NULL | |
+-----------+-------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
Can someone please help me with where the error is .
Thanks in advance.
create table posts(
post_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
author_id INT NOT NULL,
title varchar(50),
post TEXT,
data DATE,
FOREIGN KEY (author_id)
REFERENCES authors(author_id)
ON DELETE RESTRICT
)ENGINE=INNODB;
Kindly make datatype of both table's column same.
authors(author_id) and post(author_id)
Or
Make authors table first and then execute above query.
I had tried below query it's worked for me.
create table posts(
post_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
author_id INT NOT NULL,
title varchar(50),
post TEXT,
data DATE,
FOREIGN KEY (author_id)
REFERENCES labels(id)
ON DELETE RESTRICT
)ENGINE=INNODB;
Hope this will helps.
I have 3 tables:
create table comuni(
comune varchar(20) primary key,
cap char(5) not null,
abitanti int not null
)ENGINE=InnoDB;
create table mercati(
ubicazione varchar(20) not null,
comune varchar(20) not null,
primary key(ubicazione,comune),
foreign key(comune) references comuni(comune)
)ENGINE=InnoDB;
create table posteggi(
identificativo char(3) not null,
mq int not null,
CHECK(mq>=3),
acquistato bool not null DEFAULT 1,
ubicazione varchar(20) not null,
comune varchar(20) not null,
codice_fiscale char(16),
primary key(identificativo,ubicazione,comune),
foreign key(ubicazione,comune) references mercati(ubicazione,comune),
foreign key(codice_fiscale) references commercianti(codice_fiscale)
)ENGINE=InnoDB;
In the first table I've insert two rows
+-----------+-------+----------+
| comune | cap | abitanti |
+-----------+-------+----------+
| tribano | 35020 | 6000 |
| monselice | 35023 | 5020 |
+-----------+-------+----------+
then in the second one row,
+----------------+--------+------------+----------+----------+
| ubicazione | giorno | ora_inizio | ora_fine | comune |
+----------------+--------+------------+----------+----------+
| piazza mazzini | GI | 07:00:00 | 13:00:00 | tribano |
+----------------+--------+------------+----------+----------+
but when i try to execute
insert into posteggi(identificativo,mq,ubicazione,comune)
values('10',10,'piazza mazzini','tribano');
which exist in table mercati I have this error:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (ntresold-ES.posteggi, CONSTRAINT posteggi_ibfk_1 FOREIGN KEY (ubicazione, comune) REFERENCES mercati (ubicazione, comune))
Yes, the problem was the space before "tribano", I remove it and works with the code in Pheonix's answer
SQL Fiddle
MySQL 5.5.30 Schema Setup:
create table comuni(
comune varchar(20) primary key,
cap char(5) not null,
abitanti int not null
);
create table mercati(
ubicazione varchar(20) not null,
comune varchar(20) not null,
primary key(ubicazione,comune),
foreign key(comune) references comuni(comune)
);
create table posteggi(
identificativo char(3) not null,
mq int not null,
CHECK(mq>=3),
acquistato bool not null DEFAULT 1,
ubicazione varchar(20) not null,
comune varchar(20) not null,
codice_fiscale char(16),
primary key(identificativo,ubicazione,comune),
foreign key(ubicazione,comune) references mercati(ubicazione,comune)
);
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)
);