MySQL Database Creation, multiple foreign key errors? - mysql

So I'm trying to create a database in mySQL. I have a bunch of create table statements and a bunch of alter table statements. However, about half of the alter table statements are randomly giving me the 1215 "cannot add foreign key constraint" error, which is about as useful as a doctor telling me I have a broken bone and not telling me which one. Anyways, here is one of the ones that fails:
ALTER TABLE trip_instance ADD FOREIGN KEY (Trip_ID) REFERENCES signups(Trip_ID);
And here are the relevant create statements for that specific one. I made sure to specify that the columns are primary keys.
CREATE TABLE Trip_Instance (Instance_ID INT, Trip_Date DATE, Trip_ID INT, Employee_Leader VARCHAR(50), Employee_assistant VARCHAR(50),PRIMARY KEY(Instance_ID, Trip_ID));
CREATE TABLE Signups (Customer_ID INT, Trip_ID INT, Insurance_Form BOOLEAN, PRIMARY KEY (Customer_ID, Insurance_Form, Trip_ID));
EDIT:
So I used:
set foreign_key_checks=0;
Without really knowing what it does, and instead of error code 1215, I now get a bunch of 1822/1825 error codes about indexes, but even when I add index statements to the create table statements, it fails telling me the same issue.
I'm just going to put all my statements below, maybe there is some big thing I'm missing:
CREATE DATABASE OAG_Club;
USE OAG_Club;
CREATE TABLE Customer (customer_ID INT, Name VARCHAR(50), Home_Phone VARCHAR(10), Work_Phone VARCHAR(10), DOB DATE, Address VARCHAR(50), Customer_Type VARCHAR(50), Sponsor_ID INT, PRIMARY KEY(customer_ID));
CREATE TABLE Signups (Customer_ID INT, Trip_ID INT, Insurance_Form BOOLEAN, PRIMARY KEY (Customer_ID, Insurance_Form, Trip_ID));
CREATE TABLE Trip_Instance (Instance_ID INT, Trip_Date DATE, Trip_ID INT, Employee_Leader VARCHAR(50), Employee_assistant VARCHAR(50),PRIMARY KEY(Instance_ID, Trip_ID));
CREATE TABLE Trip_Type (Trip_ID INT, Trip_Name VARCHAR(50), DIFF_lvl INT, Trip_Fee INT, Trip_Length INT, PRIMARY KEY (Trip_ID));
CREATE TABLE Rental_Agreement (Agreement_Number INT, Start_Date DATE, customer_ID INT, employee_ID INT, PRIMARY KEY (Agreement_Number));
CREATE TABLE Rental_Detail (Expected_Return DATE, Real_Return DATE, item_number INT, agreement_num INT);
CREATE TABLE Inventory (Item_Number INT, `Condition` VARCHAR(50), equip_name VARCHAR(50), PRIMARY KEY (Item_Number));
CREATE TABLE Equipment (Equip_Name VARCHAR(50), Student_Fee FLOAT, FacStaffAl_Fee FLOAT, Guest_Fee FLOAT, PRIMARY KEY (Equip_Name));
CREATE TABLE OAG_Employee (Employee_ID INT, Employee_Name VARCHAR(50), Start_Date DATE, End_Date DATE, Position_ID INT, PRIMARY KEY (Employee_ID));
CREATE TABLE Position (Position_ID INT, Position_Descr VARCHAR(50), Position_Salary FLOAT, PRIMARY KEY (Position_ID));
set foreign_key_checks=0;
ALTER TABLE inventory ADD FOREIGN KEY (equip_name) REFERENCES equipment(equip_name);
ALTER TABLE customer ADD FOREIGN KEY (sponsor_ID) REFERENCES customer(sponsor_ID);*/Nope*/
ALTER TABLE signups ADD FOREIGN KEY (customer_ID) REFERENCES customer(customer_ID);
ALTER TABLE signups ADD FOREIGN KEY (Trip_ID) REFERENCES Trip_Instance(Trip_ID); /*nope*/
ALTER TABLE trip_instance ADD FOREIGN KEY (Trip_ID) REFERENCES signups(Trip_ID); /*nope*/
ALTER TABLE trip_instance ADD FOREIGN KEY (Employee_Leader) REFERENCES OAG_Employee(Employee_ID); /*nope*/
ALTER TABLE trip_instance ADD FOREIGN KEY (Employee_Assistant) REFERENCES OAG_Employee(Employee_ID); /*nope*/
ALTER TABLE rental_agreement ADD FOREIGN KEY (customer_id) REFERENCES customer(customer_id);
ALTER TABLE rental_agreement ADD FOREIGN KEY (employee_id) REFERENCES oag_employee(employee_id);
ALTER TABLE rental_detail ADD FOREIGN KEY (item_number) REFERENCES inventory(item_number);
ALTER TABLE rental_detail ADD FOREIGN KEY (agreement_num) REFERENCES rental_agreement(agreement_num); /*nope*/
ALTER TABLE oag_employee ADD FOREIGN KEY (position_ID) REFERENCES `position`(position_ID);`

A foreign key in a table has to point to a primary key in another table, not just part of the primary key. So in your table Signups, the primary key is a composite PK consisting of three columns. The foreign key in another table must have the equivalent three columns included. Generally I think it is better to set a single column PK, then it is easier to define single column FKs in other tables. By all means set a Unique constraint on the three columns if you need that, but have a separate identity column as the PK.
So for the ones it's complaining about:
ALTER TABLE customer ADD FOREIGN KEY (sponsor_ID) REFERENCES customer(sponsor_ID);
*/Nope - FK column is not referencing a PK column. PK column in customer is customer_ID. Is this a self-referencing table? If so then...*/
ALTER TABLE customer ADD FOREIGN KEY (sponsor_ID) REFERENCES customer(customer_ID);
ALTER TABLE signups ADD FOREIGN KEY (Trip_ID) REFERENCES Trip_Instance(Trip_ID);
/*nope - Trip_ID is the PK in table Trip_Type, not Trip_Instance, so...*/
ALTER TABLE signups ADD FOREIGN KEY (Trip_ID) REFERENCES Trip_Type(Trip_ID);
ALTER TABLE trip_instance ADD FOREIGN KEY (Trip_ID) REFERENCES signups(Trip_ID);
/*nope - same as above, so...*/
ALTER TABLE trip_instance ADD FOREIGN KEY (Trip_ID) REFERENCES Trip_Type(Trip_ID);
ALTER TABLE trip_instance ADD FOREIGN KEY (Employee_Leader) REFERENCES OAG_Employee(Employee_ID);
ALTER TABLE trip_instance ADD FOREIGN KEY (Employee_Assistant) REFERENCES OAG_Employee(Employee_ID);
/*nope - for both of these the FK column is varchar(50) but the referenced column is INT. What you should have is...*/
CREATE TABLE Trip_Instance (Instance_ID INT, Trip_Date DATE, Trip_ID INT, Employee_Leader_ID INT, Employee_assistant_ID INT,PRIMARY KEY(Instance_ID, Trip_ID));
ALTER TABLE trip_instance ADD FOREIGN KEY (Employee_Leader_ID) REFERENCES OAG_Employee(Employee_ID); /*nope*/
ALTER TABLE trip_instance ADD FOREIGN KEY (Employee_Assistant_ID) REFERENCES OAG_Employee(Employee_ID);
Hope this helps.

Related

Im getting an error code 1822 when i making the TAG table

create database priceTag;
use priceTag;
CREATE TABLE `ProductNumber` (
`Sku` INT auto_increment not null,
`Model` VARCHAR(100),
PRIMARY KEY (`Sku`)
);
ALTER TABLE ProductNumber AUTO_INCREMENT=60000;
CREATE TABLE `Manufacture` (
`Manufacture` VARCHAR(100),
`Model` VARCHAR(100),
`Category` VARCHAR(100),
PRIMARY KEY (`Model`)
);
CREATE TABLE `OpenBox` (
`Condtion` VARCHAR(100),
`LP` INT auto_increment not null,
`MissingItems` VARCHAR(100),
`Model_` VARCHAR(100),
FOREIGN KEY (`Model_`) REFERENCES `Manufacture`(`Model`),
PRIMARY KEY (`LP`)
);
ALTER TABLE OpenBox AUTO_INCREMENT=200000000;
CREATE TABLE `TAG` (
`SKU*` INT,
`Model*` VARCHAR(100),
`PRICE*` DECIMAL(10,2),
`LP*` INT,
`condtion*` VARCHAR(100),
FOREIGN KEY (`SKU*`) REFERENCES `ProductNumber`(`Sku`),
FOREIGN KEY (`Model*`) REFERENCES `Manufacture`(`Model`),
FOREIGN KEY (`LP*`) REFERENCES `OpenBox`(`LP`),
FOREIGN KEY (`condtion*`) REFERENCES `OpenBox`(`condtion`)
);
CREATE TABLE `Inventory` (
`INV` int,
`Sku!` int,
`Model!` VARCHAR(100),
FOREIGN KEY (`Sku!`) REFERENCES `ProductNumber`(`Sku`),
FOREIGN KEY (`Model!`) REFERENCES `Manufacture`(`Model`)
);
The column which you refer on in FOREIGN KEY (`condtion*`) REFERENCES `OpenBox`(`condtion`) (i.e. OpenBox.condtion) is not indexed.
Add needed unique index creation then create TAG table.
DEMO
I tested your code, and then ran SHOW ENGINE INNODB STATUS to get more detailed information about the error.
LATEST FOREIGN KEY ERROR
2021-12-02 09:47:16 0x700007565000 Error in foreign key constraint of table test2/tag:
FOREIGN KEY (condtion*) REFERENCES OpenBox(condtion)
):
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.
It's complaining about this foreign key:
FOREIGN KEY (`condtion*`) REFERENCES `OpenBox`(`condtion`)
The OpenBox.condtion column is not a primary key or unique key. Foreign keys must reference a key of the parent table.
You already have another foreign key in your TAGS table referencing the OpenBox table. Are you intending that the condtion column of the respective row be copied to the TAGS table? That's not how foreign keys are intended to be used.

ER_FK_NO_INDEX_PARENT: Failed to add the foreign key constraint. Missing index for constraint 'employee_ibfk_10' in the referenced table 'branch'

I try to create a table for the company database.
As I tried to add some foreign keys in there, something goes wrong.
CREATE TABLE employee (
emp_id INT PRIMARY KEY,
first_name VARCHAR(40),
last_name VARCHAR(40),
birth_day DATE,
sex VARCHAR(1),
salary INT,
super_id INT,
branch_id INT unique
);
CREATE TABLE branch (
branch_id INT PRIMARY KEY,
branch_name VARCHAR(40),
mgr_id INT,
mgr_start_date DATE,
FOREIGN KEY(mgr_id) REFERENCES employee(emp_id) ON DELETE SET NULL
);
ALTER TABLE employee
ADD FOREIGN KEY(branch_id)
REFERENCES branch(branch_id)
ON DELETE SET NULL;
ALTER TABLE employee
ADD FOREIGN KEY(super_id)
REFERENCES employee(emp_id)
ON DELETE SET NULL
The "alter table employee" part to add foreign key (branch) failed with the following statement.
ER_FK_NO_INDEX_PARENT: Failed to add the foreign key constraint. Missing index for constraint 'employee_ibfk_10' in the referenced table 'branch'
Could this be some problem with my setting?

ERROR 1005 (HY000): Can't create table 'Item_Copy' (errno: 150) unable to create table Item_Copy

I cannot create the table Item_Copy
CREATE TABLE Library
(
Library_ID int primary key,
Library_Address varchar(40),
Library_Phone bigint
);
CREATE TABLE Branch
(
Library_ID int,
Branch_Number int,
Branch_Name varchar(40),
Branch_Address varchar(40),
Branch_Phone bigint,
Branch_Hours varchar(40),
primary key (Library_ID,Branch_Number),
foreign key (Library_ID) references Library(Library_ID)
);
CREATE TABLE Item_Copy
(
Item_ID int primary key,
Copy_Number int,
Copy_Condition varchar(40),
Copy_Date_Acquired date,
Copy_Cost int,
Library_ID int,
Branch_Number int,
foreign key (Library_ID) references Branch(Library_ID),
foreign key (Branch_Number) references Branch(Branch_Number),
foreign key (Item_ID) references Item(Item_ID)
);
Just a scientific guess (will drop if it's wrong) (is based on an assumption that Item_ID definitions match):
You wanted a compound foreign key, not 2 separated FKs:
foreign key (Library_ID, Branch_Number) references Branch(Library_ID, Branch_Number)
To define a child relation, parent column must have indexed.
In the parent table Branch, Key is defined as composite.
primary key (Library_ID,Branch_Number),
But, in the child table Item_Copy, you are trying to define reference keys independent on each column.
foreign key (Library_ID) references Branch(Library_ID),
foreign key (Branch_Number) references Branch(Branch_Number),
This is only acceptable when each of these fields are referring to respective parent keys.
But Branch(Branch_Number) has no key defined in Branch table. And hence is the error.
Change:
foreign key (Library_ID) references Branch(Library_ID),
foreign key (Branch_Number) references Branch(Branch_Number),
To:
foreign key (Library_ID, Branch_Number)
references Branch(Library_ID, Branch_Number),

One of Composite primary key as Foreign key Mysql

I Have two Tables.
CREATE TABLE One(
Oneid int,
Twoid int,
data char(20),
PRIMARY KEY(Oneid,Twoid) )
Table One is Oneid and Twoid as primary key.
CREATE TABLE Two(
Twoid int,
data char(20),
PRIMARY KEY(Twoid) )
And I want to One.Twoid is foreign key for Table Two.
How to solve it.
Thank a lot.
Add the constraint in the CREATE TABLE statement:
CREATE TABLE Two(
Twoid int,
data char(20),
PRIMARY KEY (Twoid));
CREATE TABLE One(
Oneid int,
Twoid int,
data char(20),
PRIMARY KEY (Oneid,Twoid),
FOREIGN KEY (Twoid) REFERENCES Two(Twoid)); -- <== here
See fiddle.
Or use ALTER TABLE if your tables already exist:
ALTER TABLE One
ADD CONSTRAINT FK_Twoid FOREIGN KEY (Twoid) REFERENCES Two (Twoid);
See fiddle.

MySQL, MariaDB: Cannot create a table - ERROR 1005 (HY000). Something wrong with foreign key

I am new to databases and I keep getting an error when I try to create these tables. Where is a mistake?
I have found loads of questions similar to mine, but they didn't help me to resolve this problem.
CREATE TABLE IF NOT EXISTS course
(
cou_id VARCHAR(3),
course_name VARCHAR(25),
CONSTRAINT pk_course PRIMARY KEY (cou_id, course_name)
);
CREATE TABLE IF NOT EXISTS students_marks
(
stu_id INT,
student_name VARCHAR(25),
course_name VARCHAR(25),
first_mark NUMERIC(2,0),
second_mark NUMERIC(2,0),
third_mark NUMERIC(2,0),
CONSTRAINT pk_studentsmarks PRIMARY KEY (stu_id),
CONSTRAINT fk_studentsmarks_course FOREIGN KEY (course_name) REFERENCES course (course_name)
);
This is from INNODB STATUS.
LATEST FOREIGN KEY ERROR
------------------------
130603 20:17:22 Error in foreign key constraint of table testdb/students_marks:
FOREIGN KEY (course_name) REFERENCES course (course_name)
):
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.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Your primary key is set to cou_id and course_name in your course table. To add a foreign key constraint in your students_marks table, you'd have to reference both fields (and include both fields in your table definition):
CREATE TABLE IF NOT EXISTS course
(
cou_id VARCHAR(3),
course_name VARCHAR(25),
CONSTRAINT pk_course PRIMARY KEY (cou_id, course_name)
);
CREATE TABLE IF NOT EXISTS students_marks
(
stu_id INT,
student_name VARCHAR(25),
cou_id VARCHAR(3),
course_name VARCHAR(25),
first_mark NUMERIC(2,0),
second_mark NUMERIC(2,0),
third_mark NUMERIC(2,0),
CONSTRAINT pk_studentsmarks PRIMARY KEY (stu_id),
CONSTRAINT fk_studentsmarks_course FOREIGN KEY (cou_id,course_name) REFERENCES course(cou_id,course_name)
);
SQL Fiddle Demo
You are referencing only one field of a composed primary key!