Error Code 1215 Cannot Add Foreign Code Constraint - mysql

My code:
CREATE TABLE Horse (
ID SMALLINT UNSIGNED AUTO_INCREMENT,
RegisteredName VARCHAR(15),
PRIMARY KEY (ID)
);
CREATE TABLE Student (
ID SMALLINT UNSIGNED AUTO_INCREMENT,
FirstName VARCHAR(20),
LastName VARCHAR(30),
PRIMARY KEY (ID)
);
CREATE TABLE LessonSchedule (
HorseID SMALLINT UNSIGNED NOT NULL,
StudentID SMALLINT UNSIGNED NOT NULL,
LessonDateTime DATETIME NOT NULL,
Primary Key (HorseID, StudentID, LessonDateTime),
Foreign Key (HorseID) REFERENCES Horse(ID)
ON DELETE CASCADE,
Foreign Key (StudentID) REFERENCES Student(ID)
ON DELETE SET NULL
);
I'm trying to create "LessonSchedule" with these requirements:
HorseID - integer with range 0 to 65 thousand, not NULL, partial primary key, foreign key references Horse(ID)
StudentID - integer with range 0 to 65 thousand, foreign key references Student(ID)
LessonDateTime - date/time, not NULL, partial primary key
If a row is deleted from Horse, the rows with the same horse ID should be deleted from LessonSchedule automatically.
If a row is deleted from Student, the same student IDs should be set to NULL in LessonSchedule automatically.
The create horse table and create student table was given to me.
I am getting the error:
Query failed: ERROR 1215 (HY000) at line 15:
Cannot add foreign key constraint

I tested your table creation statements, and then ran SHOW ENGINE INNODB STATUS. This includes a section that gives more specific information about the reason for the failure.
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2021-11-08 10:31:11 0x700002686000 Error in foreign key constraint of table test/lessonschedule:
Foreign Key (StudentID) REFERENCES Student(ID) ON DELETE SET NULL ):
You have defined a SET NULL condition though some of the
columns are defined as NOT NULL.
This means you can't define a foreign key with ON DELETE SET NULL if the column it is based on is defined with the NOT NULL option (as a PRIMARY KEY column must be).

Related

Why Can't I form a foreign key on this?

I'am trying to add foreign key from department table to employee table. First one is done, But I can't create department table, it pops up error
ERROR 1005 (HY000): Can't create table `assignment`.`department` (errno: 150 "Foreign key constraint is incorrectly formed")
Like this.
CREATE TABLE employee
(
First_Name VARCHAR(15) NOT NULL,
Mid_Name CHAR,
Last_Name VARCHAR(15) NOT NULL,
SSN_Number CHAR(9) PRIMARY KEY NOT NULL,
Birthday DATE,
Address VARCHAR(50),
Sex CHAR CHECK(Sex='M' OR Sex='F' OR Sex='m' OR Sex='f'),
Salary Decimal(10,2) DEFAULT'800',
Supervisor_SSN CHAR(9),
Department_Number INT,
CONSTRAINT fk_employee FOREIGN KEY(Supervisor_SSN)
REFERENCES employee(SSN_Number) ON DELETE SET NULL
);
CREATE TABLE department
(
Department_Name VARCHAR(15) NOT NULL UNIQUE,
Department_Number INT PRIMARY KEY NOT NULL,
Manaager_SSN CHAR(9) NOT NULL,
Manager_Start_Date Date,
CONSTRAINT fk_manager FOREIGN KEY(Manaager_SSN)
REFERENCES employee(SSN_Number) ON DELETE SET NULL
);
I expect to add foreign key on Manaager_SSN to SSN_Number in employee table.
The option ON DELETE SET NULL is not valid if the column is declared NOT NULL. You're telling it to set the column to an impossible value.
So either change the declaration of Manaager_SSN to NULL, or change the foreign key to ON DELETE CASCADE. The former is probably more appropriate -- if the manager of a department leaves the company, you don't usually dissolve the department.
The foreign key definition includes
... ON DELETE SET NULL
^^^^^^^^
but the foreign key column is defined as non-NULL
Manaager_SSN CHAR(9) NOT NULL,
^^^^^^^^

Why I get error when trying to create table with UNIQUE or with compound PR key?

I want to create 2 tables on some machine where I downloaded mysql, and I get error when trying to create them:
CREATE TABLE Manager (
managerId int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
UNIQUE (name),
PRIMARY KEY (managerId)
);
this one fail cause of the unique from some reason...on my local machine didnt have this issue.
CREATE TABLE Contact (
managerId int NOT NULL,
contactName varchar(255) NOT NULL,
PRIMARY KEY (contactName, managerId),
FOREIGN KEY (managerId) REFERENCES Manager(managerId)
);
this one fail cause the compound pr key PRIMARY KEY (contactName, managerId)
both throw an error:
ERROR 1071 (42000): Specified key was too long; max key length is 767
bytes
if i delete the unique and the compound primary key it work...why is happening? :/

MySQL Using Same Foreign key for two different table columns

I found this thread similar to my query:
How to Link Foreign Key with Different Name
But unfortunately the answer to the question above doesn't resolve my problem as on my example tables, it doesn't create any primary key, all foreign keys only.
Here is the query for the table structure:
CREATE TABLE ref_data(
user_id INT(11) NOT NULL,
ref_id INT(11) NOT NULL,
ref_name VARCHAR(30) NOT NULL,
ref_date datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT FK_user_id FOREIGN KEY(user_id) REFERENCES client (user_id),
CONSTRAINT FK_ref_id FOREIGN KEY(ref_id) REFERENCES client (user_id),
CONSTRAINT FK_ref_name FOREIGN KEY(ref_name) REFERENCES client (firstname)
);
I get the following error:
errno: 150 "Foreign key constraint is incorrectly formed"
Here I am using user_id twice, with the first as user_id and second as ref_id. I'm also using firstname as ref_name.
This is the client table:
CREATE TABLE client (
`user_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` VARCHAR(30) NOT NULL UNIQUE KEY,
`email` VARCHAR(50) NOT NULL UNIQUE KEY,
`firstname` VARCHAR(30) NOT NULL,
`lastname` VARCHAR(30) NOT NULL,
`password` CHAR(128) NOT NULL
);
Ok, when trying to create the ref_data table, after the foreign key error, I see this:
LATEST FOREIGN KEY ERROR
------------------------ 2017-07-13 01:07:00 37ec Error in foreign key constraint of table ref_data:
FOREIGN KEY(ref_name) REFERENCES client (firstname) ):
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. Create table 'test.ref_data'
with foreign key constraint failed. There is no index in the
referenced table where the referenced columns appear as the first
columns near ' FOREIGN KEY(ref_name) REFERENCES client (firstname) )'.
What that error is basically saying: (in the bold text)
There is no index on 'firstname' for the 'client' table (the portion after the REFERENCES clause of the FOREIGN KEY
But it's a simple fix. Run this SQL on the client table:
ALTER TABLE `client` ADD INDEX(`firstname`);
... and then run the ref_data table SQL again.

How do I make a column not null and be a foreign key in MySQL

I am trying to create a table that is a foreign key of another table and make it not null, but I am running into trouble making both happen. I was able to successfully get foreign keys working that did not require NOT NULL but I can't get both working.
Here is the line giving me trouble
CONSTRAINT instructor FOREIGN KEY (id) REFERENCES Instructor(id) NOT NULL
then I get the error:
CONSTRAINT instructor FOREIGN KEY (id) REFERENCES Instructor(id) NOT NULL,
*
ERROR at line 5:
ORA-00907: missing right parenthesis
Also, I am getting a weird error when trying to create a table (note, this table is created after creating the table that contains the above error) where it fails at a very trivial part:
CREATE TABLE Enrollment (
CONSTRAINT class_id FOREIGN KEY (id) REFERENCES Class(id) NOT NULL,
CONSTRAINT member_id FOREIGN KEY (id) REFERENCES RecCenterMember(id) NOT NULL,
cost int NOT NULL
);
Then for that command I get this error:
CREATE TABLE Enrollment (
*
ERROR at line 1:
ORA-00904: : invalid identifier
How can I fix these two errors?
You need to create the column before you try creating constraints on the column.
You have:
CREATE TABLE Enrollment (
CONSTRAINT class_id FOREIGN KEY (id) REFERENCES Class(id) NOT NULL,
CONSTRAINT member_id FOREIGN KEY (id) REFERENCES RecCenterMember(id) NOT NULL,
cost int NOT NULL
);
You need:
CREATE TABLE Enrollment (
id INT NOT NULL CONSTRAINT class_id REFERENCES Class(id),
CONSTRAINT member_id FOREIGN KEY (id) REFERENCES RecCenterMember(id),
cost INT NOT NULL
);
Note that in the first line, the FOREIGN KEY isn't necessary because the column is implied. In the second line, the id is identified. You could also write:
CREATE TABLE Enrollment
(
id INT NOT NULL,
CONSTRAINT class_id FOREIGN KEY (id) REFERENCES Class(id),
CONSTRAINT member_id FOREIGN KEY (id) REFERENCES RecCenterMember(id),
cost INT NOT NULL
);
It is unusual, though not automatically wrong, to make a single column (id) be a foreign key of two tables simultaneously. It isn't clear if you actually want three columns in your table — and if you do, which column names are in your table.
You could also use the appropriate notation for an automatically allocated type in MySQL syntax (SERIAL instead of INT NOT NULL, or add AUTO_INCREMENT, etc).
Maybe you're really after:
CREATE TABLE Enrollment
(
id SERIAL,
class_id INT NOT NULL CONSTRAINT class_id REFERENCES Class(id),
member_id INT NOT NULL CONSTRAINT member_id REFERENCES RecCenterMember(id),
cost INT NOT NULL
);
This makes more sense in general. You're creating a new enrollment record for a pre-existing class, and for a pre-existing recreation centre member, and recording its cost.
Syntax diagrams vs actual behaviour
If, as Michael - sqlbot suggests — and I've no reason whatsoever to disbelieve him — MySQL recognizes but does not respond to the REFERENCES clause in a column definition in a CREATE TABLE statement but only acts on full FOREIGN KEY clauses, then you have to adjust my suggested answers from their syntactically correct but semantically ignored form to something like:
Option 1 (minimally changing the SQL from the question):
CREATE TABLE Enrollment (
id INT NOT NULL,
CONSTRAINT class_id FOREIGN KEY (id) REFERENCES Class(id),
CONSTRAINT member_id FOREIGN KEY (id) REFERENCES RecCenterMember(id),
cost int NOT NULL
);
Option 2 (what I consider the most plausible version):
CREATE TABLE Enrollment
(
id SERIAL,
class_id INT NOT NULL,
CONSTRAINT fk_class_id FOREIGN KEY (class_id) REFERENCES Class(id),
member_id INT NOT NULL,
CONSTRAINT fk_member_id FOREIGN KEY (member_id) REFERENCES RecCenterMember(id),
cost INT NOT NULL
);
Or some other variant of this syntax based on the desired table schema ignoring the FK constraints, then adding the constraints along the lines shown.
Key Point
You must define the columns before you define the foreign keys based on those columns.

mysql error 150: cannot create table

I am stuck with this error no 150 problem in mysql and I know there have been questions
which discuss this problem but I still can't find where I am wrong. Here is the database I am trying to create:
create table business (
ident varchar(40) NOT NULL,
name varchar(50) NOT NULL,
rating INT UNSIGNED NOT NULL,
PRIMARY KEY(ident)
) ENGINE=InnoDB;
create table deals (
business_id varchar(40) NOT NULL,
deals_id varchar(20) NOT NULL,
deals_title varchar(50) NOT NULL,
PRIMARY KEY (business_id, deals_id),
FOREIGN KEY (business_id) REFERENCES business(ident) ON DELETE CASCADE
) ENGINE=InnoDB;
create table d_options (
business_id varchar(40) NOT NULL,
dealid varchar(20) NOT NULL,
option_title varchar(40) NOT NULL,
PRIMARY KEY(business_id, dealid, option_title),
FOREIGN KEY(business_id) REFERENCES business(ident) ON DELETE CASCADE,
FOREIGN KEY(dealid) REFERENCES deals(deals_id)
) ENGINE=InnoDB;
I get error: ERROR 1005 (HY000): Can't create table 'test.d_options' (errno: 150)
I know for foreign key constraints to be satisfied there should be a index in the parent table as per mysql documentation, but I think that there is by default indexing
on primary key.
The result of innodb status is:
120530 0:47:48 Error in foreign key constraint of table test/d_options:
FOREIGN KEY(dealid) REFERENCES deals(deals_id)
) 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.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
Any help is appriciated.
You have a compound primary key on (business_id, deal_id) and they are indexed as a pair, but to satisfy the FK, you need another index on deal_id alone:
create table deals (
business_id varchar(40) NOT NULL,
deals_id varchar(20) NOT NULL,
deals_title varchar(50) NOT NULL,
PRIMARY KEY (business_id, deals_id),
FOREIGN KEY (business_id) REFERENCES business(ident) ON DELETE CASCADE,
/* Add an index on deals_id, separate from the compound PK */
INDEX idx_deals_id (deals_id)
) ENGINE=InnoDB;