PHP6 chapter 3 - #1215 - Cannot add foreign key constraint - mysql

I try to learn from book Professional PHP6 and in chapter 3 I need to create tables:
CREATE TABLE `entity` (
`entityid` SERIAL PRIMARY KEY NOT NULL,
`name1` varchar(100) NOT NULL,
`name2` varchar(100) NOT NULL,
`type` char(1) NOT NULL
);
and
CREATE TABLE `entityaddress` (
`addressid` SERIAL PRIMARY KEY NOT NULL,
`entityid` int,
`saddress1` varchar(255),
`saddress2` varchar(255),
`scity` varchar(255),
`cstate` char(2),
`spostalcode` varchar(10),
`stype` varchar(50),
CONSTRAINT `fk_entityaddress_entityid`
FOREIGN KEY (`entityid`) REFERENCES `entity`(`entityid`)
);
result is error: #1215 - Cannot add foreign key constraint
I check in original code for that book and there is sql file, which give me same error.
...is there anything wrong, or is something with my db in xampp?
I try to create only tables and then create relation in designers, but I got program error...
I set InnoDB engine.
Thanks for any suggestion.

The type of entityid has to be the same in both tables. SERIAL is an alias for BIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE. So change
`entityid` int,
to
`entityid` BIGINT UNSIGNED NOT NULL,

Related

MARIADB: errno: 150 "Foreign key constraint is incorrectly formed

Im trying to create 3 different tables in mariadb. I am using the exact same code I used in my localhost and it worked.
The tables name are: location, artist and murals.
I first create the location table, then I create the artist table and finally I try create the murals table because this is where my foreign keys will be, but I keep getting the following error:
ERROR 1005 (HY000): Can't create table KOMA.murals (errno: 150 "Foreign key constraint is incorrectly formed")
Creating Location Table
Create TABLE location(
l_id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
country varchar(255),
city varchar(255) NOT NULL,
address varchar(255),
a_number int(10),
zipcode int(5)
);
Creating artist Table
Create TABLE artist(
a_id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
name varchar(255) NOT NULL );
Creating murals Table
CREATE table murals (
m_id INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
title varchar(255) NOT NULL,
imageurl varchar(255) NOT NULL,
about varchar(255) NOT NULL,
year INT(4),
a_id INT(11),
l_id INT(11),
FOREIGN KEY (a_id) REFERENCES artist,
FOREIGN KEY (l_id) REFERENCES location
);
I would like to be able to create the last table with my foreign keys
When defining a foreign key, you need to point to the "parent" table and the referenced column; MySQL doesn't assume that the column has the same name.
CREATE TABLE `murals` (
`m_id` INT(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`imageurl` VARCHAR(255) NOT NULL,
`about` VARCHAR(255) NOT NULL,
`year` INT(4),
`a_id` INT(11),
`l_id` INT(11),
FOREIGN KEY (`a_id`) REFERENCES `artist`(`a_id`),
FOREIGN KEY (`l_id`) REFERENCES `location`(`l_id`)
);

MYSQL Err #1072 doesn't exist in table when specifying FK

I am new to mysql, so sorry if this is a trivial problem. Problem is when I create the second table I get the error:
key iplogger_redirect_key doesn't exist.
Here's my code:
DROP DATABASE iploggerdb;
CREATE DATABASE iploggerdb;
USE iploggerdb;
CREATE TABLE iplogger_info_table(
iplogger_redirect_key CHAR(8) PRIMARY KEY,
access_key CHAR(8) NOT NULL,
creation_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
creator_ip VARCHAR(45),
original_url VARCHAR(2000)
);
CREATE TABLE logs_table(
id INT(11) AUTO_INCREMENT,
iplogger_redirect_key FOREIGN KEY (iplogger_redirect_key) REFERENCES iplogger_info_table(iplogger_redirect_key),
logged_ip VARCHAR(45),
logged_dns_server VARCHAR(45),
logged_ip_country_city VARCHAR(200),
logged_hostname VARCHAR(200),
logged_user_agent VARCHAR(150),
logged_referrer VARCHAR(2000),
logged_ip_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
You need to correct FOREIGN KEY part:
CREATE TABLE logs_table(
id INT(11) AUTO_INCREMENT PRIMARY KEY,
iplogger_redirect_key CHAR(8),
CONSTRAINT fk_name FOREIGN KEY (iplogger_redirect_key)
REFERENCES iplogger_info_table(iplogger_redirect_key),
...
)
DBFiddle Demo

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)
);

Error code 1215 : Foreign key error : Why am I getting this?

While trying to create a foreign key MovieName in table jobinfo I get an error code : 1215 Cannot add foreign key constraint
Parent Table (contentinfo)
CREATE TABLE `contentinfo` (
`ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Movie ID',
`Name` varchar(25) DEFAULT NULL,
`Original_Language` varchar(25) DEFAULT NULL,
`Dubbed_Language` varchar(25) DEFAULT NULL,
`InputType` varchar(25) DEFAULT NULL,
`CreationTime` date DEFAULT NULL,
`VidEncodingTemplatePath` varchar(255) DEFAULT NULL,
`AudEncodingTemplatePath` varchar(255) DEFAULT NULL,
`CCEncodingTemplatePath` varchar(255) DEFAULT NULL,
`ContentType` varchar(10) DEFAULT NULL,
`RefMovieID` int(11) DEFAULT NULL COMMENT 'For dubbed movie only',
`NumberOfPartsInMovie` varchar(255) DEFAULT NULL,
`Multilingual` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=11021 DEFAULT CHARSET=latin1
Error gets thrown when I try to make a table jobinfo where there exists 2 foreign keys:
create table jobinfo( JobID int, ContainerID int,
MovieName varchar(25), FileName varchar(25), MediaType varchar(25),
ContentType varchar(25), ReelIndex int,
ReelType varchar(25), ProcessingUnitID int,
VidEncodingTemplate varchar(255), AudEncodingTemplate varchar(255),
CCEncodingTemplate varchar(255), StartIndex int,
EndIndex int, SplitIndex int, Duration int,FileSize int, Progress int,
JStatus varchar(25), QCStatus varchar(25),
QCComments varchar(255), ProcessStartTime datetime, ProcessEndTime datetime,
ProcessingStatus varchar(25), PackagingStatus varchar(30),
primary key(JobID),
foreign key (ContainerID) references contentinfo(id),
foreign key (MovieName) references contentinfo(Name));
The error gets thrown because of the statement, foreign key (MovieName) references contentinfo(Name) because when this statement is removed the command works fine. What is the reason I am getting this error?
You cannot have 2 foreign keys to the same table as a foreign key defines the unique relationship between 2 tables. Also a foreign key must uniquely identify a row in the other table, and as such always refer to a unique field, be it either through a unique constraint or a primary key (which is implicitly a unique constraint).
In your specific case: what if you had 2 movies with IDs 64 and 684, both titled "The Running Man" but one from 1987 and one from 1963, your database would be inherently corrupt because of your definition.

#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