Cannot create interconnecting table - mysql

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)

Related

SQL - Foreign key constraint is incorrectly formed

I don't know what's the problem in this code... I verified all columns names and data types but this not work
CREATE TABLE empleado (
tipo_dni VARCHAR(50) NOT NULL,
nro_dni INT NOT NULL,
nombre VARCHAR(50) NOT NULL,
apellido VARCHAR(50) NOT NULL,
direccion VARCHAR(50) NOT NULL,
telefono INT NOT NULL,
id_ciudad INT NOT NULL,
PRIMARY KEY (tipo_dni , nro_dni)
);
CREATE TABLE director (
tipo_dni VARCHAR(50) NOT NULL,
nro_dni INT NOT NULL,
PRIMARY KEY (tipo_dni, nro_dni),
FOREIGN KEY (tipo_dni)
REFERENCES empleado (tipo_dni),
FOREIGN KEY (nro_dni)
REFERENCES empleado (nro_dni)
);
ERROR
#1005 - Can't create table `tpfinal`.`director` (errno: 150 "Foreign key constraint is incorrectly formed")
Any idea ?
You primary key is:
PRIMARY KEY (tipo_dni , nro_dni)
This is a composite primary key. The foreign key reference should be composite as well:
FOREIGN KEY (tipo_dni, nro_dni)
REFERENCES empleado (tipo_dni, nro_dni)

Cannot add foreign key constraint, workbench

I used workbench to implement a database schema, but I'm getting this error when using foreign keys in a certain table.
1215 - Cannot add foreign key constraint
SQL query:
CREATE TABLE IF NOT EXISTS `Gam3ty`.`Frequently_Used_Location` (
`idFrequently_Used_Location` INT NOT NULL,
`User_idUser` INT NOT NULL,
`User_College_idCollege` INT NOT NULL,
PRIMARY KEY (`idFrequently_Used_Location`,`User_idUser`,`User_College_idCollege`),
INDEX `fk_Frequently_Used_Location_User1_idx` (`User_idUser` ASC,`User_College_idCollege` ASC),
CONSTRAINT `fk_Frequently_Used_Location_User1`
FOREIGN KEY (`User_idUser` , `User_College_idCollege`)
REFERENCES `Gam3ty`.`User` (`idUser` , `College_idCollege`)
my SQL:
CREATE SCHEMA IF NOT EXISTS `Gam3ty` DEFAULT CHARACTER SET utf8 ;
USE `Gam3ty` ;
-- -----------------------------------------------------
-- Table `Gam3ty`.`Frequently_Used_Location`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Gam3ty`.`Frequently_Used_Location` (
`idFrequently_Used_Location` INT NOT NULL,
`User_idUser` INT NOT NULL,
`User_College_idCollege` INT NOT NULL,
PRIMARY KEY (`idFrequently_Used_Location`, `User_idUser`, `User_College_idCollege`),
INDEX `fk_Frequently_Used_Location_User1_idx` (`User_idUser` ASC, `User_College_idCollege` ASC),
CONSTRAINT `fk_Frequently_Used_Location_User1`
FOREIGN KEY (`User_idUser` , `User_College_idCollege`)
REFERENCES `Gam3ty`.`User` (`idUser` , `College_idCollege`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Gam3ty`.`Location`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Gam3ty`.`Location` (
`idLocation` INT NOT NULL,
`Frequently_Used_Location_idFrequently_Used_Location` INT NOT NULL,
`Frequently_Used_Location_User_idUser` INT NOT NULL,
`Frequently_Used_Location_User_College_idCollege` INT NOT NULL,
`type` VARCHAR(45) NULL,
PRIMARY KEY (`idLocation`),
INDEX `fk_Location_Frequently_Used_Location1_idx` (`Frequently_Used_Location_idFrequently_Used_Location` ASC, `Frequently_Used_Location_User_idUser` ASC, `Frequently_Used_Location_User_College_idCollege` ASC),
CONSTRAINT `fk_Location_Frequently_Used_Location1`
FOREIGN KEY (`Frequently_Used_Location_idFrequently_Used_Location` , `Frequently_Used_Location_User_idUser` , `Frequently_Used_Location_User_College_idCollege`)
REFERENCES `Gam3ty`.`Frequently_Used_Location` (`idFrequently_Used_Location`, `User_idUser` , `User_College_idCollege`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Gam3ty`.`University`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Gam3ty`.`University` (
`idUniversity` INT NOT NULL,
`Location_idLocation` INT NOT NULL,
`Info` VARCHAR(45) NULL,
PRIMARY KEY (`idUniversity`, `Location_idLocation`),
INDEX `fk_University_Location1_idx` (`Location_idLocation` ASC),
CONSTRAINT `fk_University_Location1`
FOREIGN KEY (`Location_idLocation`)
REFERENCES `Gam3ty`.`Location` (`idLocation`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Gam3ty`.`College`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Gam3ty`.`College` (
`idCollege` INT NOT NULL,
`University_idUniversity` INT NOT NULL,
`Location_idLocation` INT NOT NULL,
`Info` VARCHAR(45) NULL,
`Staff` VARCHAR(45) NULL,
`Department` VARCHAR(45) NULL,
PRIMARY KEY (`idCollege`, `University_idUniversity`, `Location_idLocation`),
INDEX `fk_College_University1_idx` (`University_idUniversity` ASC),
INDEX `fk_College_Location1_idx` (`Location_idLocation` ASC),
CONSTRAINT `fk_College_University1`
FOREIGN KEY (`University_idUniversity`)
REFERENCES `Gam3ty`.`University` (`idUniversity`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_College_Location1`
FOREIGN KEY (`Location_idLocation`)
REFERENCES `Gam3ty`.`Location` (`idLocation`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `Gam3ty`.`User`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `Gam3ty`.`User` (
`idUser` INT NOT NULL,
`College_idCollege` INT NOT NULL,
`UserName` VARCHAR(45) NOT NULL,
`Password` VARCHAR(45) NOT NULL,
`E-mail` VARCHAR(45) NOT NULL,
`Social_media_accounts` VARCHAR(45) NULL,
`Gender` VARCHAR(45) NOT NULL,
`Job` VARCHAR(45) NOT NULL,
`Tel-num` BIGINT(11) NULL,
`Adress` VARCHAR(45) NULL,
PRIMARY KEY (`idUser`, `College_idCollege`, `UserName`),
INDEX `fk_User_College_idx` (`College_idCollege` ASC),
CONSTRAINT `fk_User_College`
FOREIGN KEY (`College_idCollege`)
REFERENCES `Gam3ty`.`College` (`idCollege`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
I checked the datatypes and they are all the same, also every foreign key is a primary key in it's original table.
Tables are created in order from top to bottom when you run a SQL script.
You can't create a foreign key that references a table that hasn't been created yet.
You must order the tables so that each table is created before any tables that reference it.
#Rahul wrote:
You need to refer all of the columns designated as primary key.
I agree this is a recommended practice, because otherwise you can create a foreign key where a given row references multiple rows in the parent table. This leads to ambiguous semantics. For instance, can you delete a row in the parent table if there's a row referencing it in the child table, but there's a second row in the parent table that satisfies the reference? This breaks the definition of referential integrity in standard SQL.
Nevertheless, InnoDB allows it. You can make a foreign key that references any left-most subset of columns of any key (unique or non-unique). It's a very bad idea, but InnoDB lets you do it and does not throw an error.
The following is crazy, but it's not an error to InnoDB:
create table foo (a int, b int, key (a, b));
create table bar (a int, foreign key (a) references foo(a));
That's cause table Gam3ty.User defines primary key on 3 columns as seen below but you are referencing only two of them. which creates partial functional dependency. You need to refer all of the columns designated as primary key
CREATE TABLE IF NOT EXISTS `Gam3ty`.`User` (
....
PRIMARY KEY (`idUser`, `College_idCollege`, `UserName`)
Your referencing table
FOREIGN KEY (`User_idUser` , `User_College_idCollege`)
REFERENCES `Gam3ty`.`User` (`idUser` , `College_idCollege`)

Error on create mysql tables?

Im trying to create a database in mysql, the first bit of my code works fine but then i get a syntax error on:
CREATE TABLE Project_Staff (
empID INT NOT NULL,
projID INT NOT NULL,
CONSTRAINT
i dont understand where is the error.
Here is my code:
CREATE TABLE Employees (
empID INT NOT NULL AUTO_INCREMENT,
empSurname VARCHAR(255) NOT NULL,
empLastname VARCHAR(255) NOT NULL,
empJobtitle VARCHAR(255) NOT NULL,
empLinemanager VARCHAR(255) NOT NULL,
CONSTRAINT pk_employees PRIMARY KEY (empID)
) ENGINE=InnoDB;
CREATE TABLE Skills (
sklID INT NOT NULL AUTO_INCREMENT,
sklName VARCHAR(255) NOT NULL,
CONSTRAINT pk_skills PRIMARY KEY (sklID)
) ENGINE = InnoDB;
CREATE TABLE Employees_Skills (
empskID INT NOT NULL AUTO_INCREMENT,
empskLevel INT NOT NULL,
sklID INT NOT NULL,
empID INT NOT NULL,
CONSTRAINT fk_employees_skills FOREIGN KEY (sklID) REFERENCES Skills(sklID),
CONSTRAINT fk_employees_skills_1 FOREIGN KEY (empID) REFERENCES Employees(empID),
CONSTRAINT pk_employees_skills PRIMARY KEY (empskID)
) ENGINE = InnoDB;
CREATE TABLE Project (
projID INT NOT NULL AUTO_INCREMENT,
projName VARCHAR(255) NOT NULL,
projDuration INT NOT NULL,
projStartdate VARCHAR (255) NOT NULL,
CONSTRAINT pk_project PRIMARY KEY (projID)
) ENGINE = InnoDB
CREATE TABLE Project_Staff (
empID INT NOT NULL,
projID INT NOT NULL,
CONSTRAINT fk_project_staff FOREIGN KEY (empID) REFERENCES Employees(empID),
CONSTRAINT fk_project_staff FOREIGN KEY (projID) REFERENCES Project(projID)
) ENGINE = InnoDB
CREATE TABLE Skill_For_Project (
sklreqDuration INT NOT NULL,
projID INT NOT NULL,
sklID INT NOT NULL,
CONSTRAINT fk_skill_for_project FOREIGN KEY (sklID) REFERENCES Skills(empID),
CONSTRAINT fk_skill_for_project FOREIGN KEY (projID) REFERENCES Project (projID)
) ENGINE = InnoDB
you have Duplicate key name 'fk_project_staff':
Duplicate key name 'fk_skill_for_project':
mising empID in skills table. you may interested in Employees(empID) in Skill_For_Project table.
You have misses Semicolon at the end of Create Table Statement
here full working code
CREATE TABLE Employees (
empID INT NOT NULL AUTO_INCREMENT,
empSurname VARCHAR(255) NOT NULL,
empLastname VARCHAR(255) NOT NULL,
empJobtitle VARCHAR(255) NOT NULL,
empLinemanager VARCHAR(255) NOT NULL,
CONSTRAINT pk_employees PRIMARY KEY (empID)
) ENGINE=InnoDB;
CREATE TABLE Skills (
sklID INT NOT NULL AUTO_INCREMENT,
sklName VARCHAR(255) NOT NULL,
CONSTRAINT pk_skills PRIMARY KEY (sklID)
) ENGINE = InnoDB;
CREATE TABLE Employees_Skills (
empskID INT NOT NULL AUTO_INCREMENT,
empskLevel INT NOT NULL,
sklID INT NOT NULL,
empID INT NOT NULL,
CONSTRAINT fk_employees_skills FOREIGN KEY (sklID) REFERENCES Skills(sklID),
CONSTRAINT fk_employees_skills_1 FOREIGN KEY (empID) REFERENCES Employees(empID),
CONSTRAINT pk_employees_skills PRIMARY KEY (empskID)
) ENGINE = InnoDB;
CREATE TABLE Project (
projID INT NOT NULL AUTO_INCREMENT,
projName VARCHAR(255) NOT NULL,
projDuration INT NOT NULL,
projStartdate VARCHAR (255) NOT NULL,
CONSTRAINT pk_project PRIMARY KEY (projID)
) ENGINE = InnoDB;
CREATE TABLE Project_Staff (
empID INT NOT NULL,
projID INT NOT NULL,
CONSTRAINT fk_project_staff FOREIGN KEY (empID) REFERENCES Employees(empID),
CONSTRAINT fk_project_staff2 FOREIGN KEY (projID) REFERENCES Project(projID)
) ENGINE = InnoDB;
CREATE TABLE Skill_For_Project (
sklreqDuration INT NOT NULL,
projID INT NOT NULL,
sklID INT NOT NULL,
CONSTRAINT fk_skill_for_project FOREIGN KEY (sklID) REFERENCES Employees(empID),
CONSTRAINT fk_skill_for_project2 FOREIGN KEY (projID) REFERENCES Project(projID)
) ENGINE = InnoDB;
http://sqlfiddle.com/#!2/d75182
As far I see, there are two issues
You missed a semicolon after create project table
CREATE TABLE Project
( projID INT NOT NULL AUTO_INCREMENT,
CONSTRAINT pk_project
PRIMARY KEY (projID) ) ENGINE = InnoDB; <-- Here
Both your constraint names (like fk_project_staff in Project_Staff table and fk_skill_for_project in Skill_For_Project table) are same; Try giving them a different name

Can two columns from one table have a foreign key to the same column in another table?

I have two tables in a database, Person and Pet.
CREATE TABLE Person (
id INT NOT NULL,
PRIMARY KEY (id)
)
CREATE TABLE Pet (
id INT NOT NULL,
original_owner INT NOT NULL,
current_owner INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (original_owner)
REFERENCES Person(id),
FOREIGN KEY (current_owner)
REFERENCES Person(id)
)
I am trying to reference the previous owner, and the current owner for each pet. I have also tried
CREATE TABLE Pet (
id INT NOT NULL,
original_owner INT NOT NULL,
current_owner INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (original_owner, current_owner)
REFERENCES Person(id, id)
)
and
CREATE TABLE Pet (
id INT NOT NULL,
original_owner INT NOT NULL,
current_owner INT NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (original_owner, current_owner)
REFERENCES Person(id)
)
but I get the following error:
Error Code: 1215. Cannot add foreign key constraint
Is this even possible to accomplish? Or would I have to create some sort of bridge table to accommodate this?
Please try the following:
CREATE TABLE IF NOT EXISTS `pet` (
`id` int(11) NOT NULL,
`original_owner` int(11) NOT NULL,
`current_owner` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `origin` (`original_owner`),
KEY `current` (`current_owner`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `pet`
ADD CONSTRAINT `pet_ibfk_2` FOREIGN KEY (`current_owner`) REFERENCES `person` (`id`),
ADD CONSTRAINT `pet_ibfk_1` FOREIGN KEY (`original_owner`) REFERENCES `person` (`id`);
The problem was the order I had the tables defined in the script. I had Pet come before Person. Once I put Person above Pet it worked fine. The example in the question was written from my head, as I didn't have the actual code handy when I posted it.

mysql innoDB error 1005

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.