MySQL: Foreign key constraint getting ignored in InnoDB - mysql

I am creating a table called fac_master which has a foreign key which refers to dept_id of dept_master. The table is getting created but foreign key is not getting enforced on this table. I also have a foreign key in dept_master which works very well but not for this table.
create table Dept_Master
( dept_id smallint unsigned auto_increment not null comment 'Department/Branch ID',
dept_name varchar(100) not null comment 'Department Name such as Computer Engineering',
prog_id tinyint unsigned not null comment 'Program ID under which this department falls',
PRIMARY KEY(dept_id),
CONSTRAINT fk_dept FOREIGN KEY(prog_id) REFERENCES Prog_Master(prog_id) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB COLLATE latin1_general_ci;
create table Fac_Master
( fac_id smallint unsigned auto_increment not null comment 'Faculty ID',
dept_id smallint unsigned not null comment 'Department Id of the department in which this faculty works',
fac_name varchar(30) not null comment 'Name of the Faculty',
fac_father_name varchar(30) comment 'Father\'s name of the faculty',
fac_surname varchar(30) comment 'Surname of the faculty',
fac_designation varchar(30) not null comment 'Designation of the faculty',
fac_mail_id varchar(50) comment 'E-mail id of the faculty',
fac_mobile bigint(10) unsigned comment 'Mobile number of the faculty',
fac_address varchar(100) comment 'Permanent Address of the faculty',
fac_status varchar(1) not null comment 'Status of Faculty: A=Active D=Deactive',
fac_joining_date date comment 'Joining Date of the Faculty',
PRIMARY KEY(fac_id),
CONSTRAINT fk_faculty FOREIGN KEY(dept_id) REFERENCES Dept_Master(dept_id) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB COLLATE latin1_general_ci;
When i try to add a value in "prog_id" of "dept_master" which is not present in the "prog_id" of "prog_master" then it gives fk constraint error which is fine but when i try to add a value in "dept_id" of "fac_master" which is not present in the "dept_id" of "dept_master" then it gets added but it should have given a fk constraint error.
I also checked foreign key constraint in information schema and found that foreign key constraint was not there for table fac_master. I am using WAMP Server 2.2 on windows 7 HP 64 bit version.
What is the problem? please help..
Edit:
alter table Fac_Master
add constraint fk_faculty FOREIGN KEY(dept_id) REFERENCES Dept_Master(dept_id) ON DELETE RESTRICT ON UPDATE RESTRICT;
using alter table as shown above works but not when used with create table. What could be the reason for it?

It appears the problem is caused by the way you escape the ' in 'Father\'s name of the faculty'. When you change it in 'Father''s name of the faculty', you'll find the foreign key constraints are correctly created.
Both ways of including a single quote are correct according to the manual, so it is a bug. See this MySQL bug ticket.

Related

Error Code: 3820. Check constraint 'chk_period_of_execution' refers to non-existing column 'd_reg_date'

CREATE TABLE IF NOT EXISTS documents (
d_reg_id VARCHAR(255) NOT NULL,
d_reg_date DATE NOT NULL,
d_id varchar(255),
d_date DATE NOT NULL,
d_theme VARCHAR(100) NOT NULL,
d_description VARCHAR(1000),
d_access VARCHAR(3) DEFAULT 'Нет',
d_control VARCHAR(3) DEFAULT 'Нет',
CONSTRAINT pk_reg_id PRIMARY KEY (d_reg_id)
) Engine=InnoDb;
CREATE TABLE IF NOT EXISTS correspondents (
c_id VARCHAR(255) NOT NULL,
c_correspondents VARCHAR(3) NOT NULL,
CONSTRAINT pk_c_id PRIMARY KEY (c_id),
CONSTRAINT fk_c_id FOREIGN KEY (c_id) REFERENCES documents(d_reg_id)
) Engine=InnoDb;
CREATE TABLE IF NOT EXISTS delivery_types (
dt_id VARCHAR(255) NOT NULL,
dt_type VARCHAR(14),
dt_period_of_execution DATE,
CONSTRAINT chk_period_of_execution CHECK (delivery_types.dt_period_of_execution > documents.d_reg_date),
CONSTRAINT pk_dt_id PRIMARY KEY (dt_id),
CONSTRAINT fk_dt_id FOREIGN KEY (dt_id) REFERENCES documents(d_reg_id)
) Engine=InnoDb;
I'm getting problem here, I need to check whether the period of execution cannot be earlier than the date of registration. Thank you in advance!
A check constraint can only check values in a single row -- it can't even refer to other rows in the same table.
For this functionality, you probably need a trigger. You can also use a user-defined function to return the value from the other table.
It is a bit hard to be more precise. A check constraint logically ensures that the data is consistent over all time, not just when the data in the table changes. It is unclear whether this is something that you only want to do when the value is inserted into delivery_types or when the value changes or when the value changes in the other table as well.

Not sure why this syntax error is happening

Hi I'm not very familiar with MySQL as I have only started using it today and I keep getting this syntax error and am not really sure what the problem is. I have attached a screenshot of the code and also pasted it below with the error in bold.
I'm sorry if this is a silly error that is easily fixed I'm just not sure how to fix it and would be very appreciative of any help.
CREATE TABLE copy (
`code` INT NOT NULL,
isbn CHAR(17) NOT NULL,
duration TINYINT NOT NULL,
CONSTRAINT pkcopy PRIMARY KEY (isbn, `code`),
CONSTRAINT fkcopy FOREIGN KEY (isbn) REFERENCES book (isbn));
CREATE TABLE student (
`no` INT NOT NULL,
`name` VARCHAR(30) NOT NULL,
school CHAR(3) NOT NULL,
embargo BIT NOT NULL,
CONSTRAINT pkstudent PRIMARY KEY (`no`));
CREATE TABLE loan (
`code` INT NOT NULL,
`no` INT NOT NULL,
taken DATE NOT NULL,
due DATE NOT NULL,
`return` DATE NULL,
CONSTRAINT pkloan PRIMARY KEY (taken, `code`, `no`),
CONSTRAINT fkloan FOREIGN KEY (`code`, `no`) REFERENCES copy, student **(**`code`, `no`));
Create the tables first, then use the ALTER TABLE statement to add the foreign keys one by one. You won't be able to call two different tables on the foreign key, so you'll have to use an ID that maps to both. Here is an example to add the foreign keys after the table has been created:
Add a new table named vendors and change the products table to include the vendor id field:
USE dbdemo;
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;

why i Cannot add foreign key constraint in MySQL Workbench

i have customer table with nid_c,nama_customer, and more field ..
second table I have kendaraan with nopol,nid_c,nama_customer, and more field ..
I try make relation between this table..
I want update data nid_c and nama_customer on kendaraan table when I update customer table.
I got error message here.
Executing SQL script in server
ERROR: Error 1215: Cannot add foreign key constraint
SQL Code:
-- -----------------------------------------------------
-- Table `BengkelBiru`.`kendaraan`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `BengkelBiru`.`kendaraan` (
`NOPOL` VARCHAR(12) NOT NULL,
`NID_C` VARCHAR(7) NULL DEFAULT NULL,
`NAMA_CUSTOMER` VARCHAR(25) NULL DEFAULT NULL,
`MERK` VARCHAR(15) NULL DEFAULT NULL,
`TYPE` VARCHAR(25) NULL DEFAULT NULL,
`CC` VARCHAR(4) NULL DEFAULT NULL,
`TAHUN` VARCHAR(4) NULL DEFAULT NULL,
`WARNA` VARCHAR(10) NULL DEFAULT NULL,
`STATUS` VARCHAR(7) NULL DEFAULT NULL,
PRIMARY KEY (`NOPOL`),
INDEX `pkk_idx` (`NAMA_CUSTOMER` ASC, `NID_C` ASC),
CONSTRAINT `FK_NID_C`
FOREIGN KEY (`NAMA_CUSTOMER` , `NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C` , `NID_C`)
ON DELETE NO ACTION
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
SQL script execution finished: statements: 14 succeeded, 1 failed
Fetching back view definitions in final form.
Nothing to fetch
Your problem is on one or both of these lines:
FOREIGN KEY (`NAMA_CUSTOMER` , `NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C` , `NID_C`)
^^^^^^^ Looks wrong s/b NAMA_CUSTOMER
I think you want this line:
REFERENCES `BengkelBiru`.`customer` (`NID_C` , `NID_C`)
to be
REFERENCES `BengkelBiru`.`customer` (`NAMA_CUSTOMER`, `NID_C`)
Why are you referring to NID_C twice in the reference? I say this because you define the foreign key as:
FOREIGN KEY (`NAMA_CUSTOMER` , `NID_C`)
and your descriptions at the top shows customer having NID_C and NAMA_CUSTOMER as columns.
However, fundamentally, why do you have Nama_customer in the kendaraan (vehicle) table at all? This doesn't seem to be 3rd normal form. You've repeated the customer name in a second table; which isn't part of the Customer's PK. Now, this may be acceptable if you want to keep the name of the customer at the time the entry is made into kendaraan; but since you're making it part of the FK... and doing cascade update/delete... it's very odd.
So maybe you just want:
FOREIGN KEY (`NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C`)
Assuming the Primary Key of Customer is NID_C
I dont think you can declare both at the same time. Try doing them separately.
CONSTRAINT `FK_NAMA_CUSTOMER`
FOREIGN KEY (`NAMA_CUSTOMER`)
REFERENCES `BengkelBiru`.`customer` (`NID_C`)
CONSTRAINT `FK_NID_C`
FOREIGN KEY (`NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C`)
There could be any possible scenario :-
1.Columns in the parent tables Can be INT UNSIGNED?
2.Data type in both tables should be same.
3.You are trying to reference a nonexistent key on the target table. Make sure that it is a key on the other table (it can be a primary or unique key).
Foregin Key Constaints

ERROR 1215 (HY000) at line 13: Cannot add foreign key constraint

I get the following error:
ERROR 1215 (HY000) at line 13: Cannot add foreign key constraint
for the following query:
ALTER TABLE client_generique
ADD CONSTRAINT client_generique_boutique_id_boutique_id
FOREIGN KEY (boutique_id) REFERENCES boutique (id)
ON DELETE SET NULL;
The boutique.id is a primary key unique not null.
The phpmyadmin structure export of the boutique table is this:
--
-- Table structure for table `boutique`
--
CREATE TABLE `boutique` (
`id` bigint(20) NOT NULL,
`nom` varchar(255) NOT NULL,
`identifiant_site` varchar(8) NOT NULL COMMENT 'the eight number identifier from the bank',
`certificate` varchar(255) NOT NULL COMMENT 'changes according to the mode, this will be used as salt in the sha1 that will be sent to the bank as the ''signature''',
`mode` varchar(10) NOT NULL COMMENT 'is the ''vads_ctx_mode'': TEST or PRODUCTION',
`payment_system` varchar(10) NOT NULL COMMENT 'CYBERPLUS OR PAYZEN for the new payment system added in end 2014'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for table `boutique`
--
ALTER TABLE `boutique`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `unique_mode_per_identifiant_idx` (`identifiant_site`,`mode`);
I do not understand. What is the reason? How to solve this problem?
Could it be that your table client_generique stores values in boutique_id which do not exist in your table boutique?
Since you try to establish a reference to boutique the values must exist in that table.
Thanks for Philipp Dietl for the solution.
It's not possible to add a foreign key constraint with a set null on delete on a not null column.
I've just modified the boutique_id column to a BIGINT (but no BIGINT NOT NULL).

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

I was working on creating some tables in database foo, but every time I end up with errno 150 regarding the foreign key. Firstly, here's my code for creating tables:
CREATE TABLE Clients
(
client_id CHAR(10) NOT NULL ,
client_name CHAR(50) NOT NULL ,
provisional_license_num CHAR(50) NOT NULL ,
client_address CHAR(50) NULL ,
client_city CHAR(50) NULL ,
client_county CHAR(50) NULL ,
client_zip CHAR(10) NULL ,
client_phone INT NULL ,
client_email CHAR(255) NULL ,
client_dob DATETIME NULL ,
test_attempts INT NULL
);
CREATE TABLE Applications
(
application_id CHAR(10) NOT NULL ,
office_id INT NOT NULL ,
client_id CHAR(10) NOT NULL ,
instructor_id CHAR(10) NOT NULL ,
car_id CHAR(10) NOT NULL ,
application_date DATETIME NULL
);
CREATE TABLE Instructors
(
instructor_id CHAR(10) NOT NULL ,
office_id INT NOT NULL ,
instructor_name CHAR(50) NOT NULL ,
instructor_address CHAR(50) NULL ,
instructor_city CHAR(50) NULL ,
instructor_county CHAR(50) NULL ,
instructor_zip CHAR(10) NULL ,
instructor_phone INT NULL ,
instructor_email CHAR(255) NULL ,
instructor_dob DATETIME NULL ,
lessons_given INT NULL
);
CREATE TABLE Cars
(
car_id CHAR(10) NOT NULL ,
office_id INT NOT NULL ,
engine_serial_num CHAR(10) NULL ,
registration_num CHAR(10) NULL ,
car_make CHAR(50) NULL ,
car_model CHAR(50) NULL
);
CREATE TABLE Offices
(
office_id INT NOT NULL ,
office_address CHAR(50) NULL ,
office_city CHAR(50) NULL ,
office_County CHAR(50) NULL ,
office_zip CHAR(10) NULL ,
office_phone INT NULL ,
office_email CHAR(255) NULL
);
CREATE TABLE Lessons
(
lesson_num INT NOT NULL ,
client_id CHAR(10) NOT NULL ,
date DATETIME NOT NULL ,
time DATETIME NOT NULL ,
milegage_used DECIMAL(5, 2) NULL ,
progress CHAR(50) NULL
);
CREATE TABLE DrivingTests
(
test_num INT NOT NULL ,
client_id CHAR(10) NOT NULL ,
test_date DATETIME NOT NULL ,
seat_num INT NOT NULL ,
score INT NULL ,
test_notes CHAR(255) NULL
);
ALTER TABLE Clients ADD PRIMARY KEY (client_id);
ALTER TABLE Applications ADD PRIMARY KEY (application_id);
ALTER TABLE Instructors ADD PRIMARY KEY (instructor_id);
ALTER TABLE Offices ADD PRIMARY KEY (office_id);
ALTER TABLE Lessons ADD PRIMARY KEY (lesson_num);
ALTER TABLE DrivingTests ADD PRIMARY KEY (test_num);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Offices FOREIGN KEY (office_id) REFERENCES Offices (office_id);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Clients FOREIGN KEY (client_id) REFERENCES Clients (client_id);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Instructors FOREIGN KEY (instructor_id) REFERENCES Instructors (instructor_id);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Cars FOREIGN KEY (car_id) REFERENCES Cars (car_id);
ALTER TABLE Lessons ADD CONSTRAINT FK_Lessons_Clients FOREIGN KEY (client_id) REFERENCES Clients (client_id);
ALTER TABLE Cars ADD CONSTRAINT FK_Cars_Offices FOREIGN KEY (office_id) REFERENCES Offices (office_id);
ALTER TABLE Clients ADD CONSTRAINT FK_DrivingTests_Clients FOREIGN KEY (client_id) REFERENCES Clients (client_id);
These are the errors that I get:
mysql> ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Cars FOREIGN KEY
(car_id) REFERENCES Cars (car_id);
ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)
I ran SHOW ENGINE INNODB STATUS which gives a more detailed error description:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
100509 20:59:49 Error in foreign key constraint of table foo/#sql-12c_4:
FOREIGN KEY (car_id) REFERENCES Cars (car_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.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
------------
I searched around on StackOverflow and elsewhere online - came across a helpful blog post here with pointers on how to resolve this error - but I can't figure out what's going wrong. Any help would be appreciated!
You should make car_id a primary key in cars.
Note: I had the same problem, and it was because the referenced field was in a different collation in the 2 different tables (they had exact same type).
Make sure all your referenced fields have the same type AND the same collation!
Check that BOTH tables have the same ENGINE. For example if you have:
CREATE Table FOO ();
and:
CREATE Table BAR () ENGINE=INNODB;
If you try to create a constraint from table BAR to table FOO, it will not work on certain MySQL versions.
Fix the issue by following:
CREATE Table FOO () ENGINE=INNODB;
Subtle, but this error got me because I forgot to declare a smallint column as unsigned to match the referenced, existing table which was "smallint unsigned." Having one unsigned and one not unsigned caused MySQL to prevent the foreign key from being created on the new table.
id smallint(3) not null
does not match, for the sake of foreign keys,
id smallint(3) unsigned not null
I got this completely worthless and uninformative error when I tried to:
ALTER TABLE `comments` ADD CONSTRAINT FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
My problem was in my comments table, user_id was defined as:
`user_id` int(10) unsigned NOT NULL
So... in my case, the problem was with the conflict between NOT NULL, and ON DELETE SET NULL.
Also both the tables need to have same character set.
for e.g.
CREATE TABLE1 (
FIELD1 VARCHAR(100) NOT NULL PRIMARY KEY,
FIELD2 VARCHAR(100) NOT NULL
)ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_bin;
to
CREATE TABLE2 (
Field3 varchar(64) NOT NULL PRIMARY KEY,
Field4 varchar(64) NOT NULL,
CONSTRAINT FORIGEN KEY (Field3) REFERENCES TABLE1(FIELD1)
) ENGINE=InnoDB;
Will fail because they have different charsets. This is another subtle failure where mysql returns same error.
I use Ubuntu linux, and in my case the error was caused by incorrect statement syntax (which I found out by typing perror 150 at the terminal, which gives
MySQL error code 150: Foreign key constraint is incorrectly formed
Changing the syntax of the query from
alter table scale add constraint foreign key (year_id) references year.id;
to
alter table scale add constraint foreign key (year_id) references year(id);
fixed it.
The referenced field must be a "Key" in the referenced table, not necessarily a primary key. So the "car_id" should either be a primary key or be defined with NOT NULL and UNIQUE constraints in the "Cars" table.
And moreover, both fields must be of the same type and collation.
I also received this error (for several tables) along with constraint errors and MySQL connecting and disconnecting when attempting to import an entire database (~800 MB). My issue was the result of The MySQL server max allowed packets being too low. To resolve this (on a Mac):
Opened /private/etc/my.conf
Under # The MySQL server, changed max_allowed_packet from 1M to 4M (You may need to experiment with this value.)
Restarted MySQL
The database imported successfully after that.
Note I am running MySQL 5.5.12 for Mac OS X (x86 64 bit).
check to make the field you are referencing to is an exact match with foreign key, in my case one was unsigned and the other was signed so i just changed them to match and this worked
ALTER TABLE customer_information
ADD CONSTRAINT fk_customer_information1
FOREIGN KEY (user_id)
REFERENCES users(id)
ON DELETE CASCADE
ON UPDATE CASCADE
Solved:
Check to make sure Primary_Key and Foreign_Key are exact match with data types.
If one is signed another one unsigned, it will be failed.
Good practice is to make sure both are unsigned int.
I was using a duplicate Foreign Key Name.
Renaming the FK name solved my problem.
Clarification:
Both tables had a constraint called PK1, FK1, etc. Renaming them/making the names unique solved the problem.
The referenced column must be an index of a single column or the first column in multi column index, and the same type and the same collation.
My two tables have the different collations. It can be shown by issuing show table status like table_name and collation can be changed by issuing alter table table_name convert to character set utf8.
all, I solved a problem and wanted to share it:
I had this error <>
The issue was in that in my statement:
alter table system_registro_de_modificacion add foreign key
(usuariomodificador_id) REFERENCES Usuario(id) On delete restrict;
I had incorrectly written the CASING: it works in Windows WAMP, but in Linux MySQL it is more strict with the CASING, so writting "Usuario" instead of "usuario" (exact casing), generated the error, and was corrected simply changing the casing.