mysql innoDB error 1005 - mysql

I'm trying to find what causes error 1005 on creation of my tables:
CREATE TABLE hospitals(
hosp_id INT NOT NULL AUTO_INCREMENT,
hosp_name VARCHAR(100) NOT NULL,
hosp_address VARCHAR(100) NOT NULL,
hosp_ph_number VARCHAR(8) NOT NULL,
PRIMARY KEY(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE transport(
tr_regnumber VARCHAR(8) NOT NULL,
tr_brand VARCHAR(15) NOT NULL,
tr_description VARCHAR(25),
hosp_id INT,
PRIMARY KEY (tr_regnumber),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE buildings(
build_id INT NOT NULL AUTO_INCREMENT,
hosp_id INT,
build_address VARCHAR(100) NOT NULL,
build_description VARCHAR(25),
PRIMARY KEY (build_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE patients(
pat_id INT NOT NULL AUTO_INCREMENT,
pat_fullname VARCHAR(150) NOT NULL,
diagnosis VARCHAR(150) NOT NULL,
emp_id INT,
pat_ph_number VARCHAR(8),
pat_address VARCHAR(100),
hosp_id INT,
pl_num INT,
PRIMARY KEY (pat_id),
FOREIGN KEY (pl_num) REFERENCES places(pl_number),
FOREIGN KEY (emp_id) REFERENCES employees(emp_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE places(
pl_number INT NOT NULL AUTO_INCREMENT,
pat_id INT NOT NULL,
hosp_id INT NOT NULL,
PRIMARY KEY (pl_number),
FOREIGN KEY (pat_id) REFERENCES patients(pat_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
CREATE TABLE employees(
emp_id INT NOT NULL AUTO_INCREMENT,
emp_fullname VARCHAR(150) NOT NULL,
emp_position VARCHAR(100) NOT NULL,
emp_ph_number VARCHAR(8),
emp_home_address VARCHAR(100),
hosp_id INT NOT NULL,
PRIMARY KEY (emp_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8;
Here are errors:
ERROR 1005 (HY000): Can't create table 'hospital_db.patients' (errno: 150)
ERROR 1005 (HY000): Can't create table 'hospital_db.places' (errno: 150)
Here's output of SHOW INNODB STATUS:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
110829 11:52:01 Error in foreign key constraint of table hospital_db/places:
FOREIGN KEY (pat_id) REFERENCES patients(pat_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8:
Cannot resolve table name close to:
(pat_id),
FOREIGN KEY (hosp_id) REFERENCES hospitals(hosp_id)
) TYPE=InnoDB CHARACTER SET=UTF8
I use MySQL v5.1.49.

This seems to be to do with the order you're creating the tables and the foreign key dependencies you have.
Try disabling foreign key checks before creating the tables and enabling them after like so:
SET foreign_key_checks = 0;
-- Your create queries here
SET foreign_key_checks = 1;
Cheers

I know this one is solved, but for the Googlers out here, I did this in mysql workbench:
Primary keys have 'not null' checked by default. Creating a foreign key in a child table and also checking it as 'not null' will cause this error. It took me ages to find this myself because its an exception of what people suggest (making sure everything in the column is of the same type as the parent key). So just leave 'not null' unchecked on the foreign key
thought this might help saving people some time :)

You create FK on table 'places' before creating this table. Table places is created after table patients which try to use table which doesn't exist yet.
It seems that you have crossing foreign keys. In this case it's better to create tables without FKs and than use ALter TABLE for adding FKs.

Related

Failed to add the foreign key constraint in MySQL: error 3780

I am getting the error:
Error Code: 3780. Referencing column 'category' and referenced column 'category_id' in foreign key constraint 'product_ibfk_1' are incompatible.
drop table if exists Provider;
drop table if exists Category;
drop table if exists Product;
create table Provider
(
privider_id serial not null primary key,
login_password varchar(20) not null
constraint passrule3 check(login_password sounds like '[A-Za-z0-9]{6,20}'),
fathersname varchar(20) not null,
name_of_contact_face varchar(10) not null,
surname varchar(15),
e_mail varchar(25) unique
constraint emailrule2 check(e_mail sounds like '[A-Za-z0-9]{10,10})\#gmail.com\s?')
);
create table Category
(
title varchar(20),
category_id serial not null primary key
);
create table Product
(
barecode serial not null primary key,
provider_id bigint not null,
manufacturer varchar(25) not null,
category_id bigint not null,
dimensions varchar(10) not null,
amount int not null,
date_of_registration datetime not null,
#constraint 'provider_for_product'
foreign key (provider_id) references Provider (provider_id) on delete restrict on update cascade,
foreign key (category_id) references Category (category_id) on delete restrict on update cascade
);
The datatypes of the two columns referenced in a foreign key constraint need to match
In MySQL, SERIAL is an alias for BIGINT UNSIGNED AUTO_INCREMENT.
To make a foreign key that references this column, it must be BIGINT UNSIGNED, not a signed BIGINT.
You might like to view a checklist of foreign key mistakes I contributed to: https://stackoverflow.com/a/4673775/20860
I also cover foreign key mistakes in more detail in a chapter of my book, SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.

MySQL foreign key constraint error code 1215

Can anyone see the problem with my create statement for table contactgroup. I keep getting error code 1215 can't create foreign key constraint.
create table contact(
ContactID int(5) not null auto_increment,
ContactName varchar(255) Not null,
ContactNumber int(5),
ContactEmail varchar(255),
primary key(ContactID))ENGINE=InnoDB DEFAULT CHARSET=utf8;
create table contactgroup(
ContactGroupID int(5) Not Null,
ContactID int(5) Not Null,
primary key(ContactGroupID),
key fk_contactgroup_ContactID (ContactID),
constraint fk_contactgroup_ContactID
foreign key(ContactID)
references contact) ENGINE=InnoDB DEFAULT CHARSET=utf8;
You need to mention both the table and the primary key column of that table when defining a foreign key constraint:
FOREIGN KEY (ContactID) REFERENCES contact(ContactID)

Cannot add foreign key constraint - MySQL ERROR 1215 (HY000)

I am trying to create database for gym management system, but I can't figure out why I am getting this error. I've tried to search for the answer here, but I couldn't find it.
ERROR 1215 (HY000): Cannot add foreign key constraint
CREATE TABLE sales(
saleId int(100) NOT NULL AUTO_INCREMENT,
accountNo int(100) NOT NULL,
payName VARCHAR(100) NOT NULL,
nextPayment DATE,
supplementName VARCHAR(250),
qty int(11),
workoutName VARCHAR(100),
sDate datetime NOT NULL DEFAULT NOW(),
totalAmount DECIMAL(11,2) NOT NULL,
CONSTRAINT PRIMARY KEY(saleId, accountNo, payName),
CONSTRAINT FOREIGN KEY(accountNo) REFERENCES accounts(accountNo) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(payName) REFERENCES paymentFor(payName) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(supplementName) REFERENCES supplements(supplementName) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(workoutName) REFERENCES workouts(workoutName) ON DELETE CASCADE ON UPDATE CASCADE
);
ALTER TABLE sales AUTO_INCREMENT = 2001;
Here is the parent tables.
CREATE TABLE accounts(
accountNo int(100) NOT NULL AUTO_INCREMENT,
accountType VARCHAR(100) NOT NULL,
firstName VARCHAR(50) NOT NULL,
lastName VARCHAR(60) NOT NULL,
birthdate DATE NOT NULL,
gender VARCHAR(7),
city VARCHAR(50) NOT NULL,
street VARCHAR(50),
cellPhone VARCHAR(10),
emergencyPhone VARCHAR(10),
email VARCHAR(150) NOT NULL,
description VARCHAR(350),
occupation VARCHAR(50),
createdOn datetime NOT NULL DEFAULT NOW(),
CONSTRAINT PRIMARY KEY(accountNo)
);
ALTER TABLE accounts AUTO_INCREMENT = 1001;
CREATE TABLE supplements(
supplementId int(100) NOT NULL AUTO_INCREMENT,
supplementName VARCHAR(250) NOT NULL,
manufacture VARCHAR(100),
description VARCHAR(150),
qtyOnHand INT(5),
unitPrice DECIMAL(11,2),
manufactureDate DATE,
expirationDate DATE,
CONSTRAINT PRIMARY KEY(supplementId, supplementName)
);
ALTER TABLE supplements AUTO_INCREMENT = 3001;
CREATE TABLE workouts(
workoutId int(100) NOT NULL AUTO_INCREMENT,
workoutName VARCHAR(100) NOT NULL,
description VARCHAR(7500) NOT NULL,
duration VARCHAR(30),
CONSTRAINT PRIMARY KEY(workoutId, workoutName)
);
ALTER TABLE workouts AUTO_INCREMENT = 4001;
CREATE TABLE paymentFor(
payId int(100) NOT NULL AUTO_INCREMENT,
payName VARCHAR(100) NOT NULL,
amount DECIMAL(11,2),
CONSTRAINT PRIMARY KEY(payId, payName)
);
ALTER TABLE paymentFor AUTO_INCREMENT = 5001;
Can you guys help me with this problem? Thanks.
If you ever want to find out, why that error was , all you have to do is run below command and look for "LATEST FOREIGN KEY ERROR"
Command to run :-
mysql> SHOW ENGINE INNODB STATUS
You will know the reason for your such errors.
For a field to be defined as a foreign key, the referenced parent field must have an index defined on it.
As per documentation on foreign key constraints:
REFERENCES parent_tbl_name (index_col_name,...)
Define an INDEX on workouts.workoutName, paymentFor.paymentName, and supplements.supplementName respectively. And make sure that child column definitions must match with those of their parent column definitions.
Change workouts table definition as below:
CREATE TABLE workouts(
workoutId int(100) NOT NULL AUTO_INCREMENT,
workoutName VARCHAR(100) NOT NULL,
description VARCHAR(7500) NOT NULL,
duration VARCHAR(30),
KEY ( workoutName ), -- <---- this is newly added index key
CONSTRAINT PRIMARY KEY(workoutId, workoutName)
);
Change supplements table definition as below:
CREATE TABLE supplements(
supplementId int(100) NOT NULL AUTO_INCREMENT,
supplementName VARCHAR(250) NOT NULL,
manufacture VARCHAR(100),
description VARCHAR(150),
qtyOnHand INT(5),
unitPrice DECIMAL(11,2),
manufactureDate DATE,
expirationDate DATE,
KEY ( supplementName ), -- <---- this is newly added index key
CONSTRAINT PRIMARY KEY(supplementId, supplementName)
);
Change paymentFor table definition as below:
CREATE TABLE paymentFor(
payId int(100) NOT NULL AUTO_INCREMENT,
payName VARCHAR(100) NOT NULL,
amount DECIMAL(11,2),
KEY ( payName ), -- <---- this is newly added index key
CONSTRAINT PRIMARY KEY(payId, payName)
);
Now, change child table definition as below:
CREATE TABLE sales(
saleId int(100) NOT NULL AUTO_INCREMENT,
accountNo int(100) NOT NULL,
payName VARCHAR(100) NOT NULL,
nextPayment DATE,
supplementName VARCHAR(250) NOT NULL,
qty int(11),
workoutName VARCHAR(100) NOT NULL,
sDate datetime NOT NULL DEFAULT NOW(),
totalAmount DECIMAL(11,2) NOT NULL,
CONSTRAINT PRIMARY KEY(saleId, accountNo, payName),
CONSTRAINT FOREIGN KEY(accountNo)
REFERENCES accounts(accountNo)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(payName)
REFERENCES paymentFor(payName)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(supplementName)
REFERENCES supplements(supplementName)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY(workoutName)
REFERENCES workouts(workoutName)
ON DELETE CASCADE ON UPDATE CASCADE
);
Refer to:
MySQL Using FOREIGN KEY Constraints
[CONSTRAINT [symbol]] FOREIGN KEY
[index_name] (index_col_name, ...)
REFERENCES tbl_name (index_col_name,...)
[ON DELETE reference_option]
[ON UPDATE reference_option]
reference_option:
RESTRICT | CASCADE | SET NULL | NO ACTION
Foreign Keys are a way of implementing relationships/constraints between columns in different tables.
There are different categories of constraints that influence how they’re enforced when a row is updated or deleted from the parent table:
◾Cascade: If a row is deleted from the parent then any rows in the child table with a matching FK value will also be deleted. Similarly for changes to the value in the parent table.
◾Restrict: A row cannot be deleted from the parent table if this would break a FK constraint with the child table. Similarly for changes to the value in the parent table.
◾No Action: Very similar to “Restrict” except that any events/triggers on the parent table will be executed before the constraint is enforced – giving the application writer the option to resolve any FK constraint conflicts using a stored procedure.
◾Set NULL: If NULL is a permitted value for the FK column in the child table then it will be set to NULL if the associated data in the parent table is updated or deleted.
◾Set Default: If there is a default value for the FK column in the child table then it will be used if the associated data in the parent table is updated or deleted. Note that this is not implemented in this version – the constraint can be added to the schema but any subsequent deletion or update to the column in the parent table will fail.
Some times you will get this error "#1215 - Cannot add foreign key constraint" because of table TYPE (InnoDB, MyISAM,..) mismatch.
So change your table type into same and try applying for foreign key constraint
mysql> ALTER TABLE table_name ENGINE=InnoDB;
mysql> ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
This might work for some people. Simply add the default character set as utf8
DEFAULT CHARACTER SET = utf8;
I was getting the same error. The reason was I was referring to a column in a table created with charset utf8 from a table created using charset latin.
The tables created using mySQL workbench create table utility have default charset latin.
Easy approach to find this out if you are using workbench is to view the table create statement of any table. You will have the default charset string at the end.
I'm not answering the above question but just for people who will run into the same mysql error.
All I did was to change the referenced table engine to innodb.
I encounter this error I add foreign key constraint for a column that has 'not null constraint' but I specified the 'on delete set null' in the foreign constraint. This is a contradiction that it may not be obvious at first.
Here are my two tables:
CREATE TABLE study (
id int(11) NOT NULL AUTO_INCREMENT primary key,
name varchar(100) NOT NULL,
introduction text,
objective varchar(250) DEFAULT NULL,
method text,
result text,
conclusion varchar(250) DEFAULT NULL,
future_action varchar(100) DEFAULT NULL
);
drop table client_study;
CREATE TABLE client_study (
id int(11) NOT NULL AUTO_INCREMENT primary key,
client_id int(11),
study_id int(11) not null, --If delete 'not null' error goes away!
contact_person int(11),
effective_date datetime DEFAULT CURRENT_TIMESTAMP,
trial_site int(11) DEFAULT NULL,
UNIQUE KEY unqidx_client_study (client_id,study_id)
);
ALTER TABLE client_study
ADD CONSTRAINT FOREIGN KEY (study_id) REFERENCES study(id)
ON DELETE SET NULL ON UPDATE CASCADE;
ERROR 1215 (HY000): Cannot add foreign key constraint
If you remove the NOT NULL constraint on the study_id column in the client_study table, the foreign key can be added. The other alternative is to keep the not null constraint on the client_table, but modify the foreign key definition to on delete no action or other choices.

Cannot create interconnecting table

i'm trying to create a table with columns that reference toward other tables.
How do i make the foreign keys?
Scheme:
Query: (not working):
CREATE TABLE gebruikers_trainingen (
gebruiker_id INT UNSIGNED NOT NULL,
training_id INT UNSIGNED NOT NULL,
gebruiker_naam VARCHAR(255) NOT NULL,
training_naam VARCHAR(255),
CONSTRAINT fk_idGebruiker FOREIGN KEY (gebruiker_id)
REFERENCES gebruikers(id),
CONSTRAINT fk_idTraining FOREIGN KEY (training_id)
REFERENCES trainingen(id),
CONSTRAINT fk_naamGebruiker FOREIGN KEY (gebruiker_naam)
REFERENCES gebruikers(voornaam),
CONSTRAINT fk_naamTraining FOREIGN KEY (training_naam)
REFERENCES trainingen(naam)
) ENGINE = INNODB;
Getting:
Error Code: 1005 Can't create table 'konecranes.gebruikers_trainingen'
(errno: 150)
EDIT:
Other tables' queries.
CREATE TABLE gebruikers (
id int unsigned NOT NULL,
voornaam varchar(255) NOT NULL,
achternaam varchar(255) NOT NULL,
account_level int unsigned NOT NULL,
PRIMARY KEY (id, voornaam)
) ENGINE = InnoDB;
CREATE TABLE trainingen (
id int unsigned NOT NULL,
naam varchar(255) NOT NULL,
PRIMARY KEY (id, naam)
) ENGINE = InnoDB;
You should add indexes on your foreign keys:
CREATE TABLE gebruikers_trainingen (
gebruiker_id INT UNSIGNED NOT NULL,
training_id INT UNSIGNED NOT NULL,
gebruiker_naam VARCHAR(255) NOT NULL,
training_naam VARCHAR(255) NOT NULL,
INDEX (gebruiker_id, gebruiker_naam),
INDEX (training_id, training_naam),
CONSTRAINT fk_idGebruiker FOREIGN KEY (gebruiker_id, gebruiker_naam)
REFERENCES gebruikers(id, voornaam),
CONSTRAINT fk_idTraining FOREIGN KEY (training_id, training_naam)
REFERENCES trainingen(id, naam)
) ENGINE = INNODB;
Has this table existed before in a different guise?
Mysql 1005 error when creating table using InnoDB engine
Hth Oli
Merging the constraints as follows did work it out. Also thanks too Justin Lurman for helping me out, had to add Indexes aswell.
CONSTRAINT fk_gebruikers FOREIGN KEY (gebruiker_id, gebruiker_naam) REFERENCES gebruikers(id, voornaam),
CONSTRAINT fk_trainingen FOREIGN KEY (training_id, training_naam) REFERENCES trainingen(id, naam)

MySQL error #1064

Hi all I can't find the error in this table creation bit, seems really straight forward to be, here's what it's giving me:
ERROR 1064 at line 3: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near 'FOREIGN KEY(courses_courseDepartmentAbbv))' at
line 8
DROP TABLE IF EXISTS courses;
CREATE TABLE courses(
courses_courseNumber INT NOT NULL AUTO_INCREMENT,
courses_courseTitle VARCHAR(25) NOT NULL,
courses_courseTeacher VARCHAR(30) NOT NULL,
courses_courseCostOfBooks DECIMAL(5,2) NOT NULL,
courses_courseDepartmentAbbv CHAR(4) NOT NULL,
PRIMARY KEY (courses_courseNumber),
FOREIGN KEY (courses_courseTeacher),
FOREIGN KEY (courses_courseDepartmentAbbv)
);
DROP TABLE IF EXISTS departments;
CREATE TABLE departments(
departments_departmentAbbv CHAR(4) NOT NULL,
departments_departmentFullName VARCHAR(15) NOT NULL,
PRIMARY KEY (departments_departmentAbbv),
FOREIGN KEY (departments_departmentAbbv) REFERENCES (courses_courseDepartmentAbbv)
);
DROP TABLE IF EXISTS teachers;
CREATE TABLE teachers(
teachers_teacherName VARCHAR(20) NOT NULL,
teachers_teacherHomeroom SMALLINT(3) NOT NULL,
teachers_teacherHomeroomGrade SMALLINT(1) NOT NULL,
teachers_teacherFullTime BOOL NOT NULL,
PRIMARY KEY (teachers_teacherName),
FOREIGN KEY (teachers_teacherName) REFERENCES (courses_courseTeacher)
);
You need to have a References after each Foreign key. You are missing that in the beginning setup of courses. Here is the documentation
I think this is more of what you want. Your order of creation was not correct. You had foreign keys in the wrong location due to this. You only set up foreign key mappings on the tables with the relations to the PK. You only need to set up the PK on your other tables. As long as you create the tables in the right order, then you can do this, as below.
So, teachers and departments have primary keys that are foreign keys within the courses table. teachers and departments does not need to worry about the foreign key. You leave that up to the table that actually has the reference (courses)
DROP TABLE IF EXISTS teachers;
CREATE TABLE teachers(
teachers_teacherName VARCHAR(20) NOT NULL,
teachers_teacherHomeroom SMALLINT(3) NOT NULL,
teachers_teacherHomeroomGrade SMALLINT(1) NOT NULL,
teachers_teacherFullTime BOOL NOT NULL,
PRIMARY KEY (teachers_teacherName)
--FOREIGN KEY (teachers_teacherName) REFERENCES courses (courses_courseTeacher)
--This is not where you set up the FK for courses
);
DROP TABLE IF EXISTS departments;
CREATE TABLE departments(
departments_departmentAbbv CHAR(4) NOT NULL,
departments_departmentFullName VARCHAR(15) NOT NULL,
PRIMARY KEY (departments_departmentAbbv)
--FOREIGN KEY (departments_departmentAbbv) REFERENCES courses (courses_courseDepartmentAbbv)
--This is not where you set up the FK for courses
);
CREATE TABLE courses(
courses_courseNumber INT NOT NULL AUTO_INCREMENT,
courses_courseTitle VARCHAR(25) NOT NULL,
courses_courseTeacher VARCHAR(30) NOT NULL,
courses_courseCostOfBooks DECIMAL(5,2) NOT NULL,
courses_courseDepartmentAbbv CHAR(4) NOT NULL,
PRIMARY KEY (courses_courseNumber),
FOREIGN KEY (courses_courseTeacher)
REFERENCES teachers (teachers_teacherName)
FOREIGN KEY (courses_courseDepartmentAbbv)
REFERENCES departments(departments_departmentAbbv)
);
You need to give a REFERENCES clause for your FOREIGN KEY clauses
FOREIGN KEY (courses_courseTeacher)
FOREIGN KEY (courses_courseDepartmentAbbv)
Define engine type that should be innodb which supports FOREIGN KEY constraints.
Follow Syntax defined here