Error #sql-890_730 when creating constraint in MySQL - php

This is my t_complaint
CREATE TABLE `t_complaint` (
`idcomplaint` int(11) NOT NULL,
`tglterima` date DEFAULT NULL,
`dept` varchar(5) DEFAULT NULL,
`pengirim` varchar(255) DEFAULT NULL,
`kontak` varchar(255) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`telp` varchar(255) DEFAULT NULL,
`jenis` varchar(45) DEFAULT NULL,
`uraian` text,
`uniqueid` varchar(9) DEFAULT NULL,
`responder` varchar(245) DEFAULT NULL,
`tgljawab` date DEFAULT NULL,
`jawaban` text,
`status` varchar(45) DEFAULT NULL,
`tglclose` date DEFAULT NULL,
`createddate` datetime DEFAULT NULL,
`createdby` varchar(45) DEFAULT NULL,
`modifieddate` datetime DEFAULT NULL,
`modifiedby` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and this is t_complaint_detail:
CREATE TABLE `t_complaint_detail` (
`no` int(11) NOT NULL,
`uniqueid` varchar(9) DEFAULT NULL,
`uploader` varchar(100) DEFAULT NULL,
`st_uploader` int(11) DEFAULT NULL,
`file_upload` text,
`original_name` text,
`status` int(11) DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
t_complaint.idcomplaint is a primary key with Auto Increment attribute
t_complaint_detail.no is a primary key with Auto Increment attribute
I'd like to connected these table via uniqueid
I've tried ALTER TABLE t_complaint_detail ADD CONSTRAINT fk_unique FOREIGN KEY ('uniqueid') REFERENCES t_complaint('uniqueid')
The query above gives error. The error is #1005 - Can't create tablebsm.#sql-890_730(errno: 150 "Foreign key constraint is incorrectly formed") (Details…)
bsm in the error is my database (my database is bsm)

Foreign key should must be a primary key in parent table. The question is, why you are adding a redundant 'uniqueId' in both the table? You can simply define a foreign key constraint like this :
t_complaint_detail ADD CONSTRAINT fk_unique FOREIGN KEY ('idcomplaint') REFERENCES t_complaint('idcomplaint').
It should work.

Error came like this
ERROR 1215 (HY000): Cannot add foreign key constraint
Because you need to create primary key in table.you can add primary key
like this
alter table t_complaint_detail modify uniqueid varchar(20) not null;
and
alter table t_complaint_detail modify uniqueid varchar(20) not null;
after it will be works
ALTER TABLE t_complaint_detail ADD CONSTRAINT fk_unique FOREIGN KEY (uniqueid) REFERENCES t_complaint(uniqueid);
please read here for more reference that will be help

It's working fine for me :
Try this :
ALTER TABLE t_complaint ADD CONSTRAINT t_complaint_detail
FOREIGN KEY ( uniqueid ) REFERENCES t_complaint( uniqueid )
Reference here :
https://www.w3schools.com/sql/sql_foreignkey.asp

Related

how to create Duplicatable entry at foreign key column in mysql

I created a site that gives you info about universities, every university has registration and exams, etc
so in database I have two columns
THE FIRST TABLE IS THE UNIVERSITIES:
CREATE TABLE `universities` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`slug` varchar(255) NOT NULL,
`views` int(11) NOT NULL DEFAULT 0,
`image` varchar(255) NOT NULL,
`banner` varchar(255) NOT NULL,
`aboutUni` text NOT NULL,
`aboutCity` text NOT NULL,
`localRank` int(5) DEFAULT NULL,
`globalRank` int(3) DEFAULT NULL,
`foundedY` int(4) NOT NULL,
`lang` varchar(10) DEFAULT NULL,
`published` tinyint(1) NOT NULL DEFAULT 1,
`created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`user_id` int(11) DEFAULT NULL,
`video` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `slug` (`slug`),
UNIQUE KEY `title` (`title`),
UNIQUE KEY `slug_2` (`slug`),
KEY `universities_ibfk_1` (`user_id`),
FULLTEXT KEY `title_2` (`title`),
CONSTRAINT `universities_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8
THE SECOND TABLE IS THE EXAMS
CREATE TABLE `bsc` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`university_id` int(11) DEFAULT NULL,
`dates` text NOT NULL,
`date_end` date DEFAULT NULL,
`date` date DEFAULT NULL,
`papers` text NOT NULL,
`info` text NOT NULL,
`method` text NOT NULL,
`link` varchar(255) DEFAULT NULL,
`register_link` varchar(255) NOT NULL,
`links` text NOT NULL,
`sort` int(2) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `university_id` (`university_id`),
UNIQUE KEY `university_id_2` (`university_id`),
CONSTRAINT `bsc_ibfk_1` FOREIGN KEY (`university_id`) REFERENCES `universities` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8mb4
NOTICE!: the tables have other columns but I think it's not important
university_id has a foreign key relation with universities.id
the problem is when I want to add tow exam to a university it appears me this error:
Duplicate entry '39' for key 'university_id'
The problem you faced Duplicate entry '39' for key 'university_id' results from trying to store in university_id a value that already existed somewhere, which is not allowed according to some constraints.
as shown in the DDL part
UNIQUE KEY `university_id` (`university_id`)
This constrain is the main cause for that error, so you need to remove that constrain by
ALTER TABLE `bsc` DROP INDEX `university_id`;
Thanks for #Tangentially, who was the first one who expected that error in his comment.
It seems that these keys are unnecesary:
UNIQUE KEY university_id (university_id),
UNIQUE KEY university_id_2 (university_id),
given that keys, you should only have distinct values in that fields.

Not able to assign On Delete Set null and on updated set Null in mysql

bank_api_uat_user Table
CREATE TABLE IF NOT EXISTS `bank_api_uat_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bank_name` varchar(255) DEFAULT NULL,
`role` varchar(10) NOT NULL,
`bank_code` char(10) NOT NULL,
`user_name` varchar(255) NOT NULL,
`password` varchar(20) NOT NULL,
`api_key` varchar(255) NOT NULL,
`Client_Secret` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_name` (`user_name`),
KEY `user_name_2` (`user_name`),
KEY `id` (`id`,`user_name`),
KEY `role` (`role`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;
create_role Table
CREATE TABLE IF NOT EXISTS `create_role` (
`date` datetime NOT NULL,
`Role_name` varchar(50) NOT NULL,
`Role_code` varchar(5) NOT NULL,
PRIMARY KEY (`Role_code`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I want to assign referential integrity to bank_api_uat_user table each time i add constraint it gives below error
MySQL said: Documentation
1215 - Cannot add foreign key constraint
Below query used to create foreign key.
ALTER TABLE `bank_api_uat_user` ADD CONSTRAINT `const_file_role` FOREIGN KEY (`role`) REFERENCES `test`.`create_role`(`Role_code`) ON DELETE SET NULL ON UPDATE SET NULL;
Its important to make a child column Null for setting null reference option.
the above queries work if role is declared as NULL
CREATE TABLE IF NOT EXISTS `bank_api_uat_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bank_name` varchar(255) DEFAULT NULL,
`role` varchar(10) NULL,
`bank_code` char(10) NOT NULL,
`user_name` varchar(255) NOT NULL,
`password` varchar(20) NOT NULL,
`api_key` varchar(255) NOT NULL,
`Client_Secret` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `user_name` (`user_name`),
KEY `user_name_2` (`user_name`),
KEY `id` (`id`,`user_name`),
KEY `role` (`role`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=36 ;
Full explanation can be find here : https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html

Unable to create foreign key in PHPmyadmin

I am trying to create foreign key in one of my table but i am getting this error can you help with this
CREATE TABLE IF NOT EXISTS `albums` (
`id` smallint(5) unsigned NOT NULL,
`url` mediumtext NOT NULL,
`year` mediumint(9) NOT NULL,
`album_name` varchar(150) NOT NULL,
`album_cover` text NOT NULL,
`tracks_id` text NOT NULL,
`category` tinyint(4) NOT NULL,
`reciter` tinyint(4) NOT NULL,
`keywords` varchar(300) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
Foreign Key Table Structure
CREATE TABLE IF NOT EXISTS `album_likes` (
`album_id` int(5) NOT NULL,
`likes` int(11) NOT NULL,
`dislikes` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Now what i did to make this foreign key is that i went to the structure of this table in phpmyadmin and then add constraint name select the columns
Here is the query
ALTER TABLE `album_likes` ADD CONSTRAINT `album_like_fk` FOREIGN KEY (`album_id`) REFERENCES `mp3script`.`albums`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
The output i got
1215 - Cannot add foreign key constraint
A foreign key requires an index on the column you are referencing, in this case albums.id.
Add the index:
CREATE INDEX ids_nn_1 on albums(id);
And you create foreign key should work

Yii2-Integrity constraint violation – yii\db\IntegrityException

Integrity constraint violation – yii\db\IntegrityException
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`jts`.`employee`, CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`))
The SQL being executed was: INSERT INTO `employee` (`client_code`, `company_name`, `emp_email`, `emp_mobile`, `emp_first_name`, `emp_last_name`) VALUES ('12345678', 'PVPPCOE', 'saurabhkulkarni2010#hotmail.com', '+449029792183', 'Saurabh', 'Kulkarni')
Error Info: Array
(
[0] => 23000
[1] => 1452
[2] => Cannot add or update a child row: a foreign key constraint fails (`jts`.`employee`, CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`))
)
I have three tables Client, Employee and create_client, out of which client and employee has two foreign keys.
This problem is showing when I try to insert data from create_client to employee which has exact same field.
What should I do so that I can insert two tables at one i.e create_client and employee
UPDATE-
Table Structure
1)client
CREATE TABLE IF NOT EXISTS `client` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8;
2)create_client
CREATE TABLE IF NOT EXISTS `create_client` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL,
`emp_email` varchar(45) NOT NULL,
`emp_mobile` varchar(45) NOT NULL,
`emp_first_name` varchar(45) NOT NULL,
`emp_last_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=utf8;
3)employee
CREATE TABLE IF NOT EXISTS `employee` (
`id` int(11) NOT NULL,
`client_code` varchar(11) NOT NULL,
`company_name` varchar(45) NOT NULL,
`emp_email` varchar(45) NOT NULL,
`emp_mobile` varchar(45) NOT NULL,
`emp_first_name` varchar(45) NOT NULL,
`emp_last_name` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
This is my table structure, first user will create client that means first it will update create_client. Now if user wants he can add many employee under one client code now user will update employee table from Yii2 dynamic form widget.
For using this widget I have created one table call client this will store only client_code and company name remaining data will go in employee table e.g emp_mobile,emp_email, emp_first_name, emp_last_name.
Now this problem is pop up when user first enters data into create_client table.
everything is working between client and employee table user able to enter as many employee as it wants using Yii2 dynamic form Widget but not working for create_client
Apparently you also have a foreign key in the employee table referencing the client_code of the client table, so you can only use client_code values that already exist in the client table.
I don't know what the structure of the create_client table looks like and what its purpose is, but based on your info I assume that you should first insert the data in client, then in employee and finally in create_client, so that every foreign key's value exists in its respective table.
If this is not correct, please post your table structures and the data or queries that could be causing this.
Edit after your comment: I assume that your table structure looks like this:
CREATE TABLE `create_client` (
`client_code` INT UNSIGNED NOT NULL,
`company_name` VARCHAR(255) NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
UNIQUE KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`),
CONSTRAINT `client_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `create_client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`company_name` VARCHAR(255) NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
However, I would suggest to use client as the parent table and move the foreign key constraint to create_client, so that both employee and create_client have a foreign key of client. I would also like to normalise this and get rid of company_name in the child tables:
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `create_client` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
UNIQUE KEY `client_code` (`client_code`),
CONSTRAINT `create_client_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
The next improvement would be to use the employee table for both unique and non-unique client_code inserts. Instead of using 2 identical tables, apart from the unique key, you could do the unique validation in Yii instead of in MySQL. You can specify the table name in the tableName() method of the CreateClient model . This will remain:
CREATE TABLE `client` (
`client_code` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`company_name` VARCHAR(255) NOT NULL,
PRIMARY KEY `client_code` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
CREATE TABLE `employee` (
`client_code` INT UNSIGNED NOT NULL,
`emp_mobile` VARCHAR(255) NOT NULL,
`emp_email` VARCHAR(255) NOT NULL,
`emp_first_name` VARCHAR(255) NOT NULL,
`emp_last_name` VARCHAR(255) NOT NULL,
KEY `client_code` (`client_code`),
CONSTRAINT `employee_ibfk_1` FOREIGN KEY (`client_code`) REFERENCES `client` (`client_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
This should allow you to use the dynamic form, with Client as the main model and Employee as the items model.
On Yii2 using IO Generator (Model) and MySQL I have found the following.
I have seen SET '' instead of SET NULL in update SQL statement(s) on field(s) with foreign key constraints that have caused a "Integrity constraint violation".
My "fix" is to add a default rule on the foreign key field in the model, like so:
public function rules()
{
return [
//
// your other rules
//
[['field_name_with_foreign_key'], 'default', 'value' => null],
];
}
Hope this helps someone.
remove all foreign key checks and simplify database.
the problem lies in your foreign key structure.
learn carefully about primary keys and foreign keys.
make new database again without foreign keys then check.

#1215 - Cannot add foreign key constraint

I'm working a project with Yiiframwork and I have this table in my data base project
CREATE TABLE IF NOT EXISTS `tbl_annonce` (
`id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`idEntreprise` tinyint(3) unsigned NOT NULL
COMMENT 'CONSTRAINT FOREIGN KEY (idEntreprise) REFERENCES tbl_entreprise(id)',
`titre` varchar(100) NOT NULL,
`detailleDiscription` varchar(5000) NOT NULL,
`categorie` varchar(100) DEFAULT NULL,
`typePoste` varchar(100) NOT NULL,
`salaireMin` varchar(80) NOT NULL,
`salaireMax` varchar(80) NOT NULL,
`niveauEtude` varchar(80) NOT NULL,
`niveauExperience` varchar(80) NOT NULL,
`langue` varchar(50) DEFAULT NULL,
`poste` varchar(50) NOT NULL,
`pays` varchar(50) NOT NULL,
`ville` varchar(50) NOT NULL,
`adresse` varchar(80) NOT NULL,
`datePublication` timestamp NOT NULL
DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`etat` varchar(50) NOT NULL,
`photo` varchar(255) NULL,
`nometr` text NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_idEntrepriseAnn`
FOREIGN KEY (idEntreprise)
REFERENCES tbl_entreprise(id)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
I only use 'comment' because I found it in a tutorial for a yii framework project.
I have got the attribute 'idEntreprise' as FK in my DB but when I entred other 'idEntreprise' that does note exist in my table entreprise it was not problem, instead it must be a problem.
So I added 'identreprise' as Fk and that have this problem now.
Hope you understand my problem :/
can any one helep me plz !!
To define a foreign key on a column, it must fulfil some conditions.
Child and parent column must have same column definition by type,
signed.
Parent column must have an index defined on it.
Make sure that
The column tbl_entreprise.id is indexed.
The column definition idEntreprise tinyint(3) unsigned in tbl_annonce matches
with that of tbl_entreprise.id
Refer to: MySQL: Foregin Key Constaints

Categories