Mysql create table with multiple foreign key on delete set null - mysql

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;

Related

Foreign Key constraint error even without a foreign key

I am getting the following error:
Error Code: 1215. Cannot add foreign key constraint
This happens even if I remove all foreign key constraints. timeline table does exist in the database, so that is not the issue.
Can't seem to figure out what would cause this problem
USE study;
CREATE TABLE IF NOT EXISTS timelineStage(
timelineStageID INT NOT NULL AUTO_INCREMENT,
timelineID TINYINT NOT NULL,
stageName VARCHAR(100) NOT NULL,
stagePredecessorID INT NULL,
isStartup TINYINT NOT NULL DEFAULT 0,
timelineStageNotes VARCHAR(500) NULL,
recCreatedByUserID INT NOT NULL,
recCreatedTimeUTC TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
recUpdatedByUserID INT NOT NULL,
recUpdatedTimeUTC TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (timelineStageID),
UNIQUE KEY IX_U_timelineStage_stageName(stageName, timelineID),
UNIQUE KEY IX_U_timelineStage_stagePredecessor(stagePredecessorID, timelineID),
CONSTRAINT FK_timelineStage_timelineID
FOREIGN KEY (timelineID)
REFERENCES timeline(timelineID)
ON UPDATE CASCADE,
CONSTRAINT FK_timelineStage_stagePredecessorID
FOREIGN KEY (stagePredecessorID)
REFERENCES timelineStage(timelineStageID)
ON UPDATE CASCADE,
CONSTRAINT FK_timelineStage_recCreatedByUserID
FOREIGN KEY (recCreatedByUserID)
REFERENCES customer.user(userID)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT FK_timelineStage_recUpdatedByUserID
FOREIGN KEY (recUpdatedByUserID)
REFERENCES customer.user(userID)
ON DELETE NO ACTION
ON UPDATE NO ACTION
)
ADDING Timeline and customer.user
USE study;
CREATE TABLE timeline(
timelineID TINYINT NOT NULL AUTO_INCREMENT,
timelineName VARCHAR(100) NOT NULL,
timelineNotes VARCHAR(500) NULL,
recCreatedByUserID INT(11) NOT NULL,
recCreatedTimeUTC DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
recUpdatedByUserID INT(11) NOT NULL,
recUpdatedTimeUTC TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (timelineID)
)
CREATE TABLE customer.user(
userID INT NOT NULL AUTO_INCREMENT,
firstName VARCHAR(100) NOT NULL,
lastName VARCHAR(100) NOT NULL,
emailAddress VARCHAR(100) NOT NULL,
PRIMARY KEY (userID))
The problem was with neither of the other tables. It was is study table (another table).
timelineStageID was set to TINYINT and in timelineStage table timelineStageID was set to INT.
Matching all to INT fixed the problem.
Carefully check every references clause whether the referenced column really is present in the table.
Also try to first create the table and then add the constraints one by one so you exactly know which one failed.
The problem is about this code: REFERENCES customer.user
You cannot create a foreign key constraint referencing a table in another database.

Not able to create table with foreign key constraints for two columns?

I have created below airports table :
CREATE TABLE airports(
airport_id int(4) unsigned AUTO_INCREMENT NOT NULL,
airport_name varchar(250),
primary key(airport_id)
)ENGINE=InnoDB;
But when I'm creating schedule table with foreign key constraints,Its not able to create. Below is the script :
CREATE TABLE schedule (
flight_id int(3) unsigned AUTO_INCREMENT NOT NULL,
origin_airport_id int(4),
destination_airport_id int(4) ,
departure_time char(15) not null,
arrival_time char(15) not null,
duration varchar(20) not null,
flight_fare decimal(9,2) not null,
PRIMARY KEY (flight_id),
FOREIGN KEY(origin_airport_id,destination_airport_id) REFERENCES airports(airport_id,airport_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
Below is the error message from show 'engine innodb status;', when I try to create the schedule table.
Error in foreign key constraint of table airport_db/schedule:
FOREIGN KEY(origin_airport_id,destination_airport_id) REFERENCES airports(airport_id,airport_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB:
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.6/en/innodb-foreign- key-constraints.html for correct foreign key definition.
Foreign keys need to reference the primary (or unique) keys of a table. There are no duplicates. And, the types have to exactly match (int doesn't match int unsigned).
So, try this instead:
CREATE TABLE schedule (
flight_id int(3) unsigned AUTO_INCREMENT NOT NULL,
origin_airport_id int(4) unsigned,
destination_airport_id int(4) unsigned,
departure_time char(15) not null,
arrival_time char(15) not null,
duration varchar(20) not null,
flight_fare decimal(9,2) not null,
PRIMARY KEY (flight_id),
FOREIGN KEY(origin_airport_id) REFERENCES airports(airport_id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY(destination_airport_id) REFERENCES airports(airport_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
Here is a SQL Fiddle.

Error Code 1022 in 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.

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.

MySQL Table order is correct, data types match, so why do I get ERROR 1005 (HY000)

I have several tables and several of them reference each other to create many-to-many relationships. I realize data types must match and table order matters when creating the foreign keys. I think I have all that accounted for. So why am I getting the ERROR 1005 (HY000) in the following:
CREATE TABLE USER (
id INT UNSIGNED NOT NULL auto_increment PRIMARY KEY,
userName VARCHAR(20) NOT NULL UNIQUE,
email VARCHAR(25) NOT NULL UNIQUE,
firstName VARCHAR(15) NOT NULL,
lastName VARCHAR(20) NOT NULL,
salt CHAR(10) NOT NULL,
HASH CHAR(40)
)ENGINE=InnoDB;
CREATE TABLE PRODUCT (
id INT UNSIGNED NOT NULL auto_increment PRIMARY KEY,
prodName VARCHAR(50) NOT NULL UNIQUE,
price DECIMAL(6,2),
availability BOOLEAN,
description VARCHAR(150) NOT NULL,
size VARCHAR(20),
weight VARCHAR(10)
)ENGINE=InnoDB;
CREATE TABLE USERENTERSPRODUCT (
userID INT UNSIGNED NOT NULL,
prodID INT UNSIGNED NOT NULL,
PRIMARY KEY (userID, prodID),
FOREIGN KEY (userID) REFERENCES USER(id) ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY (prodID) REFERENCES PRODUCT(id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB;
CREATE TABLE USERENTERSPRODUCT (
userID INT UNSIGNED NOT NULL,
prodID INT UNSIGNED NOT NULL,
PRIMARY KEY (userID, prodID),
FOREIGN KEY (userID) REFERENCES USER(id) ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY (prodID) REFERENCES PRODUCT(id) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=InnoDB;
You are specifying ON DELETE SET NULL here, but at the same time both columns have NOT NULL specified as well … that obviously can’t work.
So either remove the NOT NULL from the column definition, or change ON DELETE SET NULL to whatever matches you needs best. (Normally that should be CASCADE as well, that makes the most sense.)