Error Code 1022 in MySQL - mysql

I'm pretty new to database processing. I'm trying to create table
ASSIGNMENT (ProjectID, EmployeeNumber, HoursWorked)
ProjectID and EmployeeNumber are Composite Primary Keys of table ASSIGNMENT and Foreign Keys of tables PROJECT and EMPLOYEE (see below)
Here is my data:
CREATE TABLE IF NOT EXISTS ASSIGNMENT(
ProjectID Int(4) NOT NULL AUTO_INCREMENT,
EmployeeNumber Int(4) NOT NULL,
HoursWorked Int(4) NOT NULL,
PRIMARY KEY (ProjectID),
UNIQUE (EmployeeNumber),
KEY ProjectFK (ProjectID),
KEY EmployeeFK (EmployeeNumber),
CONSTRAINT ProjectFK FOREIGN KEY (ProjectID) REFERENCES PROJECT(ProjectID) ON DELETE CASCADE,
CONSTRAINT EmployeeFK FOREIGN KEY (EmployeeNumber) REFERENCES EMPLOYEE(EmployeeNumber)
);
I've seen a lot of examples like this one but what makes this instance unique is that MySQL doesn't allow two Primary Keys in one table so I made EmployeeNumber a UNIQUE key.
Here is the data for the entire schema:
CREATE SCHEMA IF NOT EXISTS WPC;
CREATE TABLE IF NOT EXISTS DEPARTMENT(
Department Char(30) NOT NULL DEFAULT 'Human Resources',
BudgetCode Int(20) NOT NULL,
OfficeNumber Int(10) NOT NULL,
Phone Char(12) NULL,
PRIMARY KEY (Department));
CREATE TABLE IF NOT EXISTS EMPLOYEE(
EmployeeNumber Int(4) NOT NULL AUTO_INCREMENT,
FirstName Char(25) NOT NULL,
LastName Char(25) NOT NULL,
Department Char(30) NOT NULL,
Phone Char(17) NULL,
Email VarChar(100) NOT NULL,
PRIMARY KEY (EmployeeNumber),
UNIQUE KEY Email (Email),
KEY DepartmentFK (Department),
CONSTRAINT DepartmentFK FOREIGN KEY (Department) REFERENCES DEPARTMENT(Department) ON DELETE RESTRICT ON UPDATE CASCADE
);
CREATE TABLE IF NOT EXISTS PROJECT(
ProjectID Int(4) AUTO_INCREMENT,
ProjectName Char(20) NOT NULL,
Department Char(30) NOT NULL,
MaxHours Int(14) NOT NULL DEFAULT 100,
StartDate Char(10) NOT NULL,
EndDate Char(10) NULL,
PRIMARY KEY (ProjectID),
KEY ProjectFK (Department),
CONSTRAINT ProjectFK FOREIGN KEY (Department) REFERENCES DEPARTMENT(Department) ON DELETE RESTRICT ON UPDATE CASCADE
)
ENGINE=InnoDB AUTO_INCREMENT=1000;
SET ##AUTO_INCREMENT_INCREMENT=100;
CREATE TABLE IF NOT EXISTS ASSIGNMENT(
ProjectID Int(4) NOT NULL AUTO_INCREMENT,
EmployeeNumber Int(4) NOT NULL,
HoursWorked Int(4) NOT NULL,
PRIMARY KEY (ProjectID),
UNIQUE (EmployeeNumber),
KEY ProjectFK (ProjectID),
KEY EmployeeFK (EmployeeNumber),
CONSTRAINT ProjectFK FOREIGN KEY (ProjectID) REFERENCES PROJECT(ProjectID) ON DELETE CASCADE,
CONSTRAINT EmployeeFK FOREIGN KEY (EmployeeNumber) REFERENCES EMPLOYEE(EmployeeNumber)
);
ProjectID and EmployeeNumber are composite primary keys in the table ASSIGNMENT. They are also Foreign Keys that reference tables PROJECT and EMPLOYEE.
Everything with the database is fine except for the ASSIGNMENT table. When I run the script for ASSIGNMENT I get this response:
Error Code: 1022. Can't write; duplicate key in table 'assignment'.

The names used for Foreign Key constraints must be unique in the database. You're attempting to use the same name for FKs on different tables.
You're using the name ProjectFK on the PROJECT table, and attempting to use the same name again on the ASSIGNMENT table.
Change the FK constraint name on one of the tables.

Related

Error while trying to add multiple foreign keys to single table

I am trying to create a child table that constraints 3 foreign keys from the parent but I receive an error 1215: cannot add foreign key constraint
parent table:
CREATE TABLE `Availability` (
`time_of_day` varchar(20) NOT NULL,
`day_of_week` varchar(20) NOT NULL,
`email` varchar(60) NOT NULL,
PRIMARY KEY (`time_of_day`,`day_of_week`,`email`),
KEY `email` (`email`),
CONSTRAINT `Availability_ibfk_1` FOREIGN KEY (`email`) REFERENCES `service_provider` (`email_service_provider`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
child table (which I cant build due to error mentioned above):
CREATE TABLE TEST1
(
num_request INT NOT NULL,
time_of_day VARCHAR(20) NOT NULL,
day_of_week VARCHAR(20) NOT NULL,
email VARCHAR(60) NOT NULL,
PRIMARY KEY (num_request),
Foreign key (time_of_day) references Availability(time_of_day),
Foreign key (day_of_week) references Availability(day_of_week),
Foreign key (email) references Availability(email)
);
Please show me what I'm doing wrong... Thank you all.
When you're making a foreign key to a table with a composite primary key (i.e. a key of multiple columns), you should make the foreign key composite as well.
CREATE TABLE TEST1
(
num_request INT NOT NULL,
time_of_day VARCHAR(20) NOT NULL,
day_of_week VARCHAR(20) NOT NULL,
email VARCHAR(60) NOT NULL,
PRIMARY KEY (num_request),
Foreign key (time_of_day, day_of_week, email) references Availability(time_of_day, day_of_week, email)
)
The columns of the foreign key should match the columns of the primary or unique key they reference. They should have the same number of columns, in the same order.
What you tried to do was create three separate constraints of one column each.

Can not Add External Index Constraints

This is the exact error that WAMP returns when I run the child code from an external file called entries.txt
ERROR 1215 (HY000): Can not Add External Index Constraints
I need to be able to connect the parent tables to the child table so that links can be made between the tables easily.
The question states:
Create and populate a third table called entries, again using query scripts.
This table should contain foreign keys to allow sensible links to be
made with the other two tables, together with the dates of each exam.
Parent Tables:
CREATE TABLE IF NOT EXISTS students(
student_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
first_name VARCHAR(20) NOT NULL,
middle_name VARCHAR(20),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(60) NOT NULL,
password CHAR(40) NOT NULL,
reg_date DATETIME NOT NULL,
PRIMARY KEY (student_id),
UNIQUE (email));
CREATE TABLE IF NOT EXISTS subjects(
subject_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
subject_name CHAR(30) NOT NULL,
level_of_entry VARCHAR(10) NOT NULL,
exam_board CHAR(20) NOT NULL,
PRIMARY KEY (subject_id));
Child Table:
CREATE TABLE IF NOT EXISTS entries(
date_of_exam DATETIME NOT NULL,
first_name VARCHAR,
middle_name VARCHAR,
last_name VARCHAR,
subject_name CHAR,
level_of_entry VARCHAR,
exam_board CHAR,
INDEX idx_first_name(first_name),
INDEX idx_middle_name(middle_name),
INDEX idx_last_name(last_name),
INDEX idx_subject_name(subject_name),
INDEX idx_level_of_entry(level_of_entry),
INDEX idx_exam_board(exam_board),
PRIMARY KEY (date_of_exam),
CONSTRAINT fk_first_name FOREIGN KEY (first_name) REFERENCES students(first_name),
CONSTRAINT fk_middle_name FOREIGN KEY (middle_name) REFERENCES students(middle_name),
CONSTRAINT fk_last_name FOREIGN KEY (last_name) REFERENCES students(last_name),
CONSTRAINT fk_subject_name FOREIGN KEY (subject_name) REFERENCES subjects(subject_name),
CONSTRAINT fk_level_of_entry FOREIGN KEY (level_of_entry) REFERENCES subjects(level_of_entry),
CONSTRAINT fk_exam_board FOREIGN KEY (exam_board) REFERENCES subjects(exam_board)
)ENGINE=InnoDB;
A foreign key in the child table must reference the primary key of the parent table only. You don't need to create clones of every attribute column of the parent tables, just the primary key column. If you need to read the other attributes, you'd write a query with a JOIN.
CREATE TABLE IF NOT EXISTS entries(
student_id INT UNSIGNED NOT NULL,
subject_id INT UNSIGNED NOT NULL,
date_of_exam DATETIME NOT NULL,
PRIMARY KEY (student_id, subject_id, date_of_exam),
CONSTRAINT fk_student FOREIGN KEY (student_id) REFERENCES students(student_id),
CONSTRAINT fk_subject FOREIGN KEY (subject_id) REFERENCES subjects(subject_id),
)ENGINE=InnoDB;

Mysql code runs but the foreign key values are not showing in table in phpmyadmin

My code runs in phpmyadmin but the foreign key values are not showing in table and when I update it the message shows "0 rows affected"
my table schema is:
CREATE TABLE fee_report (
fr_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
school_id INT NOT NULL,
branch_id INT NOT NULL,
student_id INT NOT NULL,
ledger VARCHAR(55),
bill_no VARCHAR(255) NOT NULL,
fdate date NOT NULL,
receipt_no VARCHAR(255) NOT NULL,
dr float NOT NULL,
cr float NOT NULL,
balance float NOT NULL,
particulars VARCHAR(155),
updated TIMESTAMP NOT NULL,
CONSTRAINT fk_frschool FOREIGN KEY (school_id)
REFERENCES school(school_id),
CONSTRAINT fk_frbranch FOREIGN KEY (branch_id)
REFERENCES branch(branch_id),
CONSTRAINT fk_frstudent FOREIGN KEY (student_id)
REFERENCES student(student_id)
) ENGINE = INNODB;
INSERT INTO fee_report(school_id,branch_id,student_id,ledger,bill_no,fdate,dr,balance,particulars,feetype)
VALUES(1,1,13,'TGS007','SESNOV1020',CURDATE(),'2850','-14450','11','Tuition Fee,Transport Fee,Smart Class Fee,SA-1 Exam Fee')
Why foreign keys school_id, branch_id and student_id are not showing in table
and when I remove foreign key constraint the values are visible in table

Mysql create table with multiple foreign key on delete set null

I am trying to create a database with multiple foreign keys with delete/ update constraints, but I got a error code 1005 with following sql scripts:
CREATE TABLE Worker (
WorkerID smallint auto_increment,
WorkerType varchar(45) NOT NULL,
WorkerName varchar(45) NOT NULL,
Position varchar(45) NOT NULL,
TaxFileNumber int NOT NULL,
Address varchar(100) ,
Phone varchar(20) ,
SupervisorID smallint ,
PRIMARY KEY (WorkerID),
FOREIGN KEY (SupervisorID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
CREATE TABLE Grape (
GrapeID smallint NOT NULL,
GrapeType varchar(45) NOT NULL,
JuiceConversionRatio int,
StorageContainer ENUM('Stainless Steel Tank','Oak Barrel'),
AgingRequirement int,
PRIMARY KEY (GrapeID)
)Engine=InnoDB;
CREATE TABLE Vineyard (
VineyardID smallint auto_increment,
VineyardName VARCHAR(45) NOT NULL,
FarmerID smallint NOT NULL,
GrapeID smallint NOT NULL,
ComeFrom varchar(45) NOT NULL,
HarvestedAmount int,
RipenessPercent int,
PRIMARY KEY (VineyardID),
FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
The error code says that fail to create the Vineyard table, I just want to know the proper format for creating multiple foreign keys with delete/update control.
Your foreign key rule is ON DELETE SET NULL but your column definition is NOT NULL.
Either change your column definition and remove the NOT NULL part or overthink your foreign key rule. That works:
CREATE TABLE Vineyard (
VineyardID smallint auto_increment,
VineyardName VARCHAR(45) NOT NULL,
FarmerID smallint,
GrapeID smallint,
ComeFrom varchar(45) NOT NULL,
HarvestedAmount int,
RipenessPercent int,
PRIMARY KEY (VineyardID),
FOREIGN KEY (FarmerID) REFERENCES Worker(WorkerID)
ON DELETE SET NULL
ON UPDATE CASCADE,
FOREIGN KEY (GrapeID) REFERENCES Grape(GrapeID)
ON DELETE SET NULL
ON UPDATE CASCADE
)Engine=InnoDB;
SQLFiddle demo
Try with create table(innoDB enginer) without foreign key and use the update table with constraint syntax, for example:
ALTER TABLE `vineyard`
ADD CONSTRAINT `relation_farmer_has_many_vineyards`
FOREIGN KEY (`farmer_id`)
REFERENCES `worker` (`worker_id`)
ON DELETE SET NULL
ON UPDATE CASCADE;
Reference:
http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
Trick: is not recommended to use capital letters(or camel case) in the names of the tables that the behavior differs from the operating system being used:
http://dev.mysql.com/doc/refman/5.1/en/identifier-case-sensitivity.html
Visit :
https://developer.android.com/training/basics/data-storage/databases.html#DefineContract
Cursor c = db.query(
FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
Visit :
http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
CREATE TABLE `ffxi_characterJob` (
`serverID` int(11) NOT NULL,
`userid` int(10)unsigned NOT NULL,
`characterName` varchar(255) NOT NULL,
`jobAbbr` char(4) NOT NULL,
`jobLevel` int(11) default '0',
PRIMARY KEY (`serverID`,`userid`,`characterName`,`jobAbbr`),
INDEX (`jobAbbr`),
CONSTRAINT FOREIGN KEY (`serverID`,`userid`,`characterName`) REFERENCES `ffxi_characters` (`serverID`,`userid`,`characterName`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FOREIGN KEY (`jobAbbr`) REFERENCES `ffxi_jobType` (`jobAbbr`) ON DELETE CASCADE ON UPDATE CASCADE
) TYPE=InnoDB;

#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