MySQL Error - Cannot add foreign key constraint - mysql

I know this question has been asked several times but it seemed like the problem was due to different data types between parent and child rows.
In my case, the data types are the same but I'm still getting the error. Here's my code
CREATE TABLE STUDENT_2(
StudentNumber INT NOT NULL AUTO_INCREMENT,
StudentName VARCHAR(50) NULL,
Dorm VARCHAR(50) NULL,
RoomType VARCHAR(50) NOT NULL,
CONSTRAINT STUDENTPK PRIMARY KEY(StudentNumber)
);
CREATE TABLE DORM_COST(
RoomType VARCHAR(50) NOT NULL,
DormCost DECIMAL(7,2) NULL,
CONSTRAINT DORM_COSTPK PRIMARY KEY(RoomType),
CONSTRAINT DORM_COST_FK FOREIGN KEY(RoomType)
REFERENCES STUDENT_2(RoomType)
ON UPDATE CASCADE
ON DELETE CASCADE
);
Where DORM_COSTS' foreign key cannot be added.
Thanks!

You want the foreign key reference on the table that has the foreign key, not the primary key. So, that would be:
CREATE TABLE DORM_COST (
RoomType VARCHAR(50) NOT NULL,
DormCost DECIMAL(7,2) NULL,
CONSTRAINT DORM_COSTPK PRIMARY KEY(RoomType)
);
CREATE TABLE STUDENT_2(
StudentNumber INT NOT NULL AUTO_INCREMENT,
StudentName VARCHAR(50) NULL,
Dorm VARCHAR(50) NULL,
RoomType VARCHAR(50) NOT NULL,
CONSTRAINT STUDENTPK PRIMARY KEY(StudentNumber),
CONSTRAINT fk_student2_roomtype FOREIGN KEY (RoomType) REFERENCES DORM_COST(RoomType)
);
Here is a db<>fiddle that shows that this works.
That said your data model seems quite strange.
I would expect a table called RoomTypes to have a primary key of RoomTypeId.
I would expect dorm_cost to have dates, because costs can vary from year to year.
I would expect different dorms to have similar room types -- singles, doubles, and so on.
I would expect those room types to vary, perhaps, by dorm.

Related

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

Why am I unable to add these foreign keys?
I'm trying to make clientName and employeeId both foreign keys in the events table. I realize I may not need clientEmail, but my error is currently showing at clientName.
CREATE TABLE client
(
clientName VARCHAR(50) PRIMARY KEY NOT NULL,
clientID INT NOT NULL auto_increment,
clientEmail VARCHAR(50) NOT NULL,
clientPass VARCHAR(50) NOT NULL,
phone VARCHAR(50) NOT NULL
);
CREATE TABLE admin
(
Name VARCHAR(50) NOT NULL,
adminId INT NOT NULL PRIMARY KEY auto_increment,
adminPass VARCHAR(50) NOT NULL,
adminEmail VARCHAR(50) NOT NULL
);
CREATE TABLE employee
(
Name VARCHAR(50) NOT NULL,
employeeId INT NOT NULL PRIMARY KEY auto_increment,
employeePass VARCHAR(50) NOT NULL,
employeeEmail VARCHAR(50) NOT NULL
);
CREATE TABLE event
(
eventId INT PRIMARY KEY auto_increment,
employeeId INT NOT NULL,
clientName VARCHAR(50) NOT NULL,
clientEmail VARCHAR(50) NOT NULL,
Constraint client_fk_name
Foreign Key (clientName)
references client (clientName),
Constraint client_fk_email
Foreign Key (clientEmail)
references client (clientEmail),
Constraint employee_fk_id
Foreign Key (employeeId)
references employee (employeeId)
);
Only these four tables.
So, one way to deal with this is to call the attribute in the parent table UNIQUE. This solves this error. However, as a side effect in my current experience, upon inserting into the database you may experience problems if your values are not unique (possibly obviously). But if you can guarantee uniqueness then just add Unique and you will be fine.
Unique specifies an attribute as a candidate key. Essentially it’s saying this could have been the primary key, but we chose something else.

trying to relate two table together

so pretty new to SQL I created 2 tables which I wanted to be related to one another but I'm getting an error "#1215 - Cannot add foreign key constraint" can someone point me to the right direction of this problem?
CREATE TABLE movie(
id INT(1) NOT NULL AUTO_INCREMENT,
nearname VARCHAR(25) NOT NULL,
release_date DATE NOT NULL,
lang VARCHAR(10) NOT NULL,
PRIMARY KEY(id),
CONSTRAINT same_movie FOREIGN KEY(id) REFERENCES movie_cast(movie_id)
);
CREATE TABLE movie_cast(
movie_id INT(1) NOT NULL AUTO_INCREMENT,
director_name VARCHAR(20) NOT NULL,
actor_name VARCHAR(20) NOT NULL,
actress_name VARCHAR(20) NOT NULL,
PRIMARY KEY(movie_id),
CONSTRAINT same_movie FOREIGN KEY(movie_id) REFERENCES movie(id)
);
You need to refer to the same column name as the primary key. In this case, it is called id:
CONSTRAINT same_movie FOREIGN KEY(movie_id) REFERENCES movie_cast(id)
Of course, your DDL doesn't define movie_cast. So, I am guessing the second table should be something like:
CREATE TABLE movie_cast (
id INT NOT NULL AUTO_INCREMENT,
movie_id int not null,
cast_name varchar(255)
PRIMARY KEY(id),
CONSTRAINT fk_movie_cast_movie FOREIGN KEY(movie_id) REFERENCES movie(movie_id)
);

errno: 150 "Foreign key constraint is incorrectly formed" Nothing helps

sorry for maybe stupid question, but I stack with my sql query. Tried out many methods to avid it but still have error 150. I've created 3 tables and one with foreighn keys:
Table users
create table users(
id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
cname varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
);
Table behaviours
CREATE TABLE behaviours (
id int(2) AUTO_INCREMENT PRIMARY KEY,
bName varchar(100) NOT NULL
);
Table severytys
CREATE TABLE severitys (
id int(2) AUTO_INCREMENT PRIMARY KEY,
severity varchar(10) NOT NULL
);
And here it shows errors:
CREATE TABLE child_behaviours(
id int(11) primary key auto_increment,
name varchar(50) not null,
cname varchar(50) not null,
bName varchar(100) NOT NULL,
severity varchar(10) NOT NULL,
start_at datetime,
stop_at datetime null,
FOREIGN KEY (id) REFERENCES users(id),
FOREIGN KEY (bName) REFERENCES behaviours(bName),
FOREIGN KEY (severity) REFERENCES severitys(severity)
);
Will be really pleasent to have an answer to this issue
You can only create a FK on a column that is both UNIQUE and NOT NULL. This is usually, but not always, the primary key of the referenced table.
If you reference anything other than the PK, you need a really really good reason.
(I'd even add to that, that you need a really really good reason to use anything other than an INT or a couple INTs as a PK...)
Now, child_behaviours has several errors:
Duplication of columns already present in users. If you reference users by its id, there is no need to duplicate the columns.
Reference to behaviors(bName) instead of using its id
same thing for reference to severity
Also, there is the generic mistake of using "id" columns. Please call them "user_id", "severity_id", etc, and then call them the same in your references. This will make your life much easier, and avoid stuff like:
SELECT foo.id AD foo_id, bar.id AS bar_id FROM foo JOIN bar ON ...
You have to refer to a primary key, when building a foreign key
CREATE TABLE child_behaviours(
userId int not null,
behaviourId int NOT NULL,
severityId int NOT NULL,
start_at datetime not null,
stop_at datetime,
FOREIGN KEY (userId) REFERENCES users(id),
FOREIGN KEY (behaviourId) REFERENCES behaviours(id),
FOREIGN KEY (severityId) REFERENCES severitys(id)
);

Foreign key for multiple tables and columns?

I have been learning about Foreign keys and I wanted to know if the way I used it is correct in the example below:
CREATE TABLE user(
id INT(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(20) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE items(
i_id INT(11) NOT NULL AUTO_INCREMENT,
name TINYTEXT NOT NULL,
price DECIMAL(8,2) NOT NULL,
PRIMARY KEY (i_id)
);
CREATE TABLE user_purchase(
i_id INT(11) NOT NULL,
name TINYTEXT NOT NULL,
id INT(11) NOT NULL,
FOREIGN KEY (i_id) REFERENCES items(i_id),
FOREIGN KEY (name) REFERENCES items(name),
FOREIGN KEY (id) REFERENCES user(id)
);
Thanks
Now, how can I get maximum information from just the Foreign Key if I use, let's say, PHP?
You don't have to include item name in both tables. This is called a denormalized solution.
You should have it only in the items table and only refer to the id, then if you need the name also you can join it based on the primary key(id).
Otherwise it is totally OK in my opinion.
CREATE TABLE user(
id INT(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(20) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE items(
i_id INT(11) NOT NULL AUTO_INCREMENT,
name TINYTEXT NOT NULL,
price DECIMAL(8,2) NOT NULL,
PRIMARY KEY (i_id)
);
CREATE TABLE user_purchase(
i_id INT(11) NOT NULL,
name TINYTEXT NOT NULL,
id INT(11) NOT NULL,
FOREIGN KEY (i_id) REFERENCES items(i_id),
FOREIGN KEY (id) REFERENCES user(id)
);
Sometimes when performance is critical you have to use denormalized tables. It can be much faster.
Normalization is important to avoid different anomalies.
If you have tables in a high level normal form then your tables won't be redundant and wont have these anomalies. For example if you have something stored in multiple locations you have to look after to keep all the redundant data up to date. This gives you a chance to do this incorrectly and end up having different anomalies.
In your situation having a foreign key helps you to keep data integrity but without a foreign key for the name you would be able to have items with names in the purchases that are not present in the items table.
This is a kind of anomaly.
There are many kinds of this, best to avoid them as long as you can.
Read more here about anomalies
In some cases you must denoramalize. So store some data redundantly because of performance issues. This way you can save some join operations that could consume much time.
Details of normalization are covered by topics of different normal forms:
NF0, NF1, NF2, NF3 and BCNF
Normal forms in detail
For further details about the mathematical foundations of loseless decomposition to higher normal forms see "Functional dependencies". This is going to help you understand why you can keep the ids "redundant". Virtually they are necessary redundancy, since you need them in order to be able to later rebuild the original dataset. This is going to be the definition for the different normal forms. What level of this redundancy is allowed?
Functional Dependencies
you've got an i_id as a primary key, you don't need to set up a name as a foreign key. and btw foreign key has to reference to unique attribute.
CREATE TABLE `user`(
id INT(11) NOT NULL AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(20) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE items(
i_id INT(11) NOT NULL AUTO_INCREMENT,
`name` TINYTEXT UNIQUE NOT NULL,
price DECIMAL(8,2) NOT NULL,
PRIMARY KEY (i_id)
);
CREATE TABLE user_purchase(
i_id INT(11) NOT NULL,
`name` TINYTEXT NOT NULL,
id INT(11) NOT NULL,
FOREIGN KEY (i_id) REFERENCES items(i_id),
FOREIGN KEY (id) REFERENCES `user`(id)
);

#1005 - Can't create table on ALTER TABLE when connecting table via FOREIGN KEY

I am working on a homework assignment. I have to build a database for a video store. All of the following works:
CREATE TABLE Stock
(
PKStock_ID VARCHAR(8) NOT NULL,
FKTitle VARCHAR(8) NOT NULL,
NoOfDVD INT(10) NOT NULL,
NoOfVHS INT(10) NOT NULL,
PRIMARY KEY (PKStock_ID)
);
CREATE TABLE Inventory
(
PKUnique_ID VARCHAR(8) NOT NULL,
DistributorSerialNo VARCHAR(8) NOT NULL,
Distributor_ID VARCHAR(8) NOT NULL,
FKTitle_ID VARCHAR(8) NOT NULL,
InStock CHAR(1) NOT NULL,
DateOut TIMESTAMP,
DateBack TIMESTAMP,
Customer_ID VARCHAR(8) NOT NULL,
Rental_Price DECIMAL(4,2) NOT NULL,
PRIMARY KEY (PKUnique_ID)
);
CREATE TABLE Movie
(
PKTitle_ID VARCHAR(8) NOT NULL,
FKTitle_ID VARCHAR(8) NOT NULL,
Title VARCHAR(30),
Genre VARCHAR(8),
YearReleased INT,
Length INT,
PRIMARY KEY (PKTitle_ID)
);
CREATE TABLE Actors
(
PKActor_ID VARCHAR(8) NOT NULL,
FKActor_ID VARCHAR(8) NOT NULL,
Actors VARCHAR(30),
PRIMARY KEY (PKActor_ID)
);
CREATE TABLE Awards
(
PKAward_ID VARCHAR(8) NOT NULL,
FKAward_ID VARCHAR(8) NOT NULL,
Awards VARCHAR(30),
PRIMARY KEY (PKAward_ID)
);
CREATE TABLE Directors
(
PKDirector_ID VARCHAR(8) NOT NULL,
FKDirector_ID VARCHAR(8) NOT NULL,
Directors VARCHAR(30),
PRIMARY KEY (PKDirector_ID)
);
CREATE TABLE ElectronicCatalogue
(
PKElectronicCatalogue VARCHAR(8) NOT NULL,
FKDistributor_ID VARCHAR(8) NOT NULL,
DistributorSerialNo VARCHAR(8) NOT NULL,
Price DECIMAL(6,2) NOT NULL,
PRIMARY KEY (PKElectronicCatalogue)
);
CREATE TABLE Distributors
(
PKDistributor_ID VARCHAR(8) NOT NULL,
FKDistributor_ID VARCHAR(8) NOT NULL,
NameOfDistributer VARCHAR(30) NOT NULL,
Horror CHAR(1) NOT NULL,
Drama CHAR(1) NOT NULL,
Comedy CHAR(1) NOT NULL,
Action CHAR(1) NOT NULL,
Thrillers CHAR(1) NOT NULL,
PRIMARY KEY (PKDistributor_ID)
);
CREATE TABLE Customers
(
PKCustomer_ID VARCHAR(8) NOT NULL,
FKUnique_ID VARCHAR(8) NOT NULL,
Name VARCHAR(30),
Address VARCHAR(100),
Phone INT NOT NULL,
PRIMARY KEY (PKCustomer_ID)
);
CREATE TABLE Fees
(
PKFee_ID VARCHAR(8) NOT NULL,
FK_ID VARCHAR(8) NOT NULL,
Damages DECIMAL(10,2) NOT NULL,
Late DECIMAL(10,2) NOT NULL,
PRIMARY KEY (PKFee_ID)
);
ALTER TABLE Stock
ADD FOREIGN KEY (FKTitle)
REFERENCES Inventory(PKUnique_ID);
ALTER TABLE Movie
ADD FOREIGN KEY (FKTitle_ID)
REFERENCES Stock (PKStock_ID);
ALTER TABLE Actors
ADD FOREIGN KEY (FKActor_ID)
REFERENCES Movie (PKTitle_ID);
ALTER TABLE Awards
ADD FOREIGN KEY (FKAward_ID)
REFERENCES Movie (PKTitle_ID);
ALTER TABLE Directors
ADD FOREIGN KEY (FKDirector_ID)
REFERENCES Movie (PKTitle_ID);
ALTER TABLE ElectronicCatalogue
ADD FOREIGN KEY (FKDistributor_ID)
REFERENCES Inventory (PKUnique_ID);
ALTER TABLE Distributors
ADD FOREIGN KEY (FKDistributor_ID)
REFERENCES ElectronicCatalogue (PKElectronicCatalogue);
I next want to connect the Inventory table to the customers table. When I do the following:
ALTER TABLE Customers
ADD FOREIGN KEY (FKUnique_ID)
REFERENCES Inventory (Customer_ID);
I get this error:
#1005 - Can't create table 'mm.#sql-9f69_110' (errno: 150)
What am I doing wrong?
Foreign key should point to a unique column (primary key or unique). Your Inventory (Customer_ID) is not unique.
I think you are trying to :
ALTER TABLE Inventory
ADD CONSTRAINT fk1_Inv FOREIGN KEY (Customer_ID)
REFERENCES Customers (PKCustomer_ID);
Not sure why you didn't get the full message but there's a command line tool bundled with MySQL that provides further information about cryptic error messages like this (or you can just Google for the error code):
C:>perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
If you have the SUPER privilege, you can get further details with this query:
show engine innodb status
And in this case you see this:
LATEST FOREIGN KEY ERROR
------------------------
130226 21:00:25 Error in foreign key constraint of table test/#sql-1d98_1:
FOREIGN KEY (FKUnique_ID)
REFERENCES Inventory (Customer_ID):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
So you are missing an index as explained.
Edit: As other answers point out, if there's no index it's because you're linking to the wrong column.
As Álvaro G. Vicario says you are missing an index, this is because you are not correctly using foreign keys.
ALTER TABLE Customers
ADD FOREIGN KEY (FKUnique_ID)
REFERENCES Inventory (Customer_ID);
This should be:
ALTER TABLE Inventory
ADD FOREIGN KEY (Customer_ID)
REFERENCES Customer(PKCustomer_ID);
The foreign key checks if the customer in the Inventory table actually exists in the Customers table. Thus Inventory here is the table you want to add the foreign key too and it references in primary key in the Customer table.
What you are trying to do is reference the Customer_ID in Inventory, which is just an VARCHAR(8)column and not an Primary Key (Index).
You should double check your other alter statements as well.
This turns out that you have different collation settings between these tables. In my case we had latin_swedish_ci and utf8_general_ci