mysql cannot add foreign key for unknown reason - mysql

I cannot a add a foreign key constraint. the sql i m running is -
ALTER TABLE image_shout ADD CONSTRAINT `fk_image` FOREIGN KEY (image_id)
REFERENCES images(image_id);
the collation and the data types( int(10) ) are same in the two tables.
mysql says -
Error Code: 1215. Cannot add foreign key constraint
The images table structure -
CREATE TABLE `images` (
`image_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`image_name` varchar(100) CHARACTER SET latin1 NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`caption` varchar(450) CHARACTER SET latin1 DEFAULT NULL,
`image_visibility` int(10) unsigned NOT NULL,
`album_id` int(10) unsigned NOT NULL,
`album_view` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`album_thumb_view` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`image_id`),
KEY `Index_2` (`album_id`),
CONSTRAINT `FK_images_1` FOREIGN KEY (`album_id`) REFERENCES `photo_album` (`Album_ID`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=4314 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
The image_shout table -
CREATE TABLE `image_shout` (
`auto_id` int(11) NOT NULL AUTO_INCREMENT,
`shout_id` int(11) DEFAULT NULL,
`image_id` int(10) DEFAULT NULL,
PRIMARY KEY (`auto_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1132 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
UPDATE -
The new error after changing the image_id column to unsigned is -
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails
(`void`.`#sql-36b_7285`, CONSTRAINT `fk_image` FOREIGN KEY (`image_id`)
REFERENCES `images` (`image_id`) ON DELETE SET NULL ON UPDATE CASCADE)
Regards

Is because the image_id in table images is defined as unsigned
`image_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
and in image_shout not
`image_id` int(10) DEFAULT NULL,
Change both columns to the same data type and it should work.

The problem is below. According to the documentation, a foreign key must be indexed. Further, a foreign key should reference the KEY of another table. Not just a column. Try using auto_id as the constraint if you don't wish to change your table structure.
Please see MySQL Documentation for the list of requirements of a Foreign Key constraint.
CREATE TABLE `image_shout` (
`auto_id` int(11) NOT NULL AUTO_INCREMENT,
`shout_id` int(11) DEFAULT NULL,
`image_id` int(10) DEFAULT NULL,
PRIMARY KEY (`auto_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1132 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Related

Foreign key constraint is incorrectly formed (MySQL)

I am trying to create a database for this project: https://sourceforge.net/projects/ess/
I've created a database called ess via PHPmyadmin and when I run the SQL query to create the tables I get an error on the second table areasuper.
The error is: "#1005 - Can't create table `ess.areasuper` (errno: 150 "Foreign key constraint is incorrectly formed")"
I don't really understand what I have been able to find online regarding this type of error so I'm hoping someone here can spell it out for me.
Also, I'm not sure how much info anyone will need to understand and replicate this so please let me know what to include if I have missed anything.
Thank you.
CREATE TABLE areas (
area_id int(11) unsigned NOT NULL auto_increment,
area_name varchar(20) default NULL,
area_desc varchar(100) NOT NULL default '',
area_templ text,
PRIMARY KEY (area_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table `areasuper`
--
CREATE TABLE areasuper (
as_id int(11) unsigned NOT NULL auto_increment,
as_area_id int(11) unsigned NOT NULL default '0',
as_uid int(11) unsigned NOT NULL default '0',
PRIMARY KEY (as_id),
KEY as_area_id (as_area_id),
KEY as_uid (as_uid),
CONSTRAINT areasuper_ibfk_1 FOREIGN KEY (as_area_id) REFERENCES areas (area_id) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT areasuper_ibfk_2 FOREIGN KEY (as_uid) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table `assignments`
--
CREATE TABLE assignments (
assign_id int(10) unsigned NOT NULL auto_increment,
assign_uid int(10) unsigned NOT NULL default '0',
assign_pid int(10) unsigned NOT NULL default '0',
assign_eid int(10) unsigned NOT NULL default '0',
PRIMARY KEY (assign_id),
KEY assign_uid (assign_uid),
KEY assign_pid (assign_pid),
KEY assign_eid (assign_eid),
CONSTRAINT assignments_ibfk_1 FOREIGN KEY (assign_uid) REFERENCES users (user_id) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT assignments_ibfk_2 FOREIGN KEY (assign_pid) REFERENCES positions (pos_id) ON DELETE NO ACTION ON UPDATE CASCADE,
CONSTRAINT assign_assign_eid_fk FOREIGN KEY (assign_eid) REFERENCES `events` (event_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table `availabletimes`
--
CREATE TABLE availabletimes (
avail_id int(10) unsigned NOT NULL auto_increment,
avail_uid int(11) unsigned NOT NULL default '0',
avail_day char(1) NOT NULL default '',
avail_start time NOT NULL default '00:00:00',
avail_end time NOT NULL default '00:00:00',
PRIMARY KEY (avail_id),
KEY avail_uid (avail_uid),
CONSTRAINT availabletimes_ibfk_1 FOREIGN KEY (avail_uid) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table `dayoff`
--
CREATE TABLE dayoff (
day_id int(11) unsigned NOT NULL auto_increment,
day_uid int(11) unsigned NOT NULL default '0',
day_start date NOT NULL default '0000-00-00',
day_end date NOT NULL default '0000-00-00',
day_desc varchar(50) NOT NULL default '',
PRIMARY KEY (day_id),
KEY day_uid (day_uid),
CONSTRAINT dayoff_ibfk_1 FOREIGN KEY (day_uid) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table `events`
--
CREATE TABLE `events` (
event_id int(11) unsigned NOT NULL auto_increment,
event_start time NOT NULL default '00:00:00',
event_end time NOT NULL default '00:00:00',
event_area_id int(11) unsigned NOT NULL default '0',
event_name varchar(50) NOT NULL default '',
event_comments text,
event_date date NOT NULL default '0000-00-00',
PRIMARY KEY (event_id),
KEY event_area_id (event_area_id),
CONSTRAINT events_ibfk_1 FOREIGN KEY (event_area_id) REFERENCES areas (area_id) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table `positions`
--
CREATE TABLE positions (
pos_id int(10) unsigned NOT NULL auto_increment,
pos_area_id int(10) unsigned NOT NULL default '0',
pos_name varchar(20) NOT NULL default '',
pos_desc varchar(100) NOT NULL default '',
PRIMARY KEY (pos_id),
KEY pos_area_id (pos_area_id),
CONSTRAINT positions_ibfk_1 FOREIGN KEY (pos_area_id) REFERENCES areas (area_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table `supervisors`
--
CREATE TABLE supervisors (
super_emp int(11) unsigned NOT NULL default '0',
super_super int(11) unsigned NOT NULL default '0',
KEY super_emp (super_emp),
CONSTRAINT supervisors_ibfk_1 FOREIGN KEY (super_emp) REFERENCES users (user_id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table `types`
--
CREATE TABLE `types` (
type_id int(10) unsigned NOT NULL auto_increment,
type_name varchar(10) NOT NULL default '',
PRIMARY KEY (type_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Table structure for table `users`
--
CREATE TABLE users (
user_id int(10) unsigned NOT NULL auto_increment,
user_name varchar(10) NOT NULL default '',
user_pass varchar(40) NOT NULL default '',
user_first varchar(10) NOT NULL default '',
user_last varchar(20) NOT NULL default '',
user_email varchar(50) NOT NULL default '',
user_phone1 bigint(20) NOT NULL default '0',
user_phone2 bigint(20) default NULL,
user_type int(11) unsigned NOT NULL default '0',
user_pay_rate float(5,2) default '0.00',
PRIMARY KEY (user_id),
KEY user_type (user_type),
CONSTRAINT users_ibfk_1 FOREIGN KEY (user_type) REFERENCES `types` (type_id) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Foreign key failure when inserting into child table ( referencing composite unique index)

I have problem when trying to insert row into my child database table.
Here is my parent table:
CREATE TABLE `payables` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`type` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`currency_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `payables_id_type_unique` (`id`,`type`),
KEY `payables_currency_id_foreign` (`currency_id`),
CONSTRAINT `payables_currency_id_foreign` FOREIGN KEY (`currency_id`) REFERENCES `currencies` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
And here is my child table:
CREATE TABLE `pays` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`transaction_id` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned NOT NULL,
`value` int(10) unsigned NOT NULL,
`status_id` int(10) unsigned NOT NULL,
`payable_id` int(10) unsigned NOT NULL,
`payable_type` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `pays_transaction_id_unique` (`transaction_id`),
KEY `pays_user_id_index` (`user_id`),
KEY `pays_status_id_index` (`status_id`),
KEY `pays_payable_id_index` (`payable_id`),
KEY `pays_payable_type_index` (`payable_type`),
KEY `pays_payable_id_payable_type_foreign` (`payable_id`,`payable_type`),
CONSTRAINT `pays_payable_id_payable_type_foreign` FOREIGN KEY (`payable_id`, `payable_type`) REFERENCES `payables` (`id`, `type`) ON UPDATE CASCADE,
CONSTRAINT `pays_status_id_foreign` FOREIGN KEY (`status_id`) REFERENCES `statuses` (`id`) ON UPDATE CASCADE,
CONSTRAINT `pays_transaction_id_foreign` FOREIGN KEY (`transaction_id`) REFERENCES `transactions` (`id`) ON UPDATE CASCADE,
CONSTRAINT `pays_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
That is the table I'm trying to seed, the parent table is already seeded.
I'm using laravel query builder to create these tables, so if anyone more experienced with databases could review the code, that would be much appreciated, thanks.
Sorry just missed that i was inserting different data type to my column.

Error 1215: Can't add foreign key constraint (InnoDB)

I'm struggling around to create a foreign key with the following query:
alter table `users` add constraint `users_sales_partner_id_foreign` foreign key (`sales_partner_id`) references `structures` (`sales_partner_id`) on update cascade
InnoDB log says, it can't match this index:
2017-02-27 10:25:47 Error in foreign key constraint of
table website_backend/users: foreign key
(sales_partner_id) references structures (sales_partner_id) on update cascade:
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.
I have already checked typos and data type incompatibility, but everything seems to be alright:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`profile_id` int(10) unsigned NOT NULL,
`sales_partner_id` int(11) NOT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`state` enum('pending','confirmed','active','deactivated') COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `users_profile_id_unique` (`profile_id`),
UNIQUE KEY `users_sales_partner_id_unique` (`sales_partner_id`),
UNIQUE KEY `users_email_unique` (`email`),
CONSTRAINT `users_profile_id_foreign` FOREIGN KEY (`profile_id`) REFERENCES `profiles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
CREATE TABLE `structures` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`sales_partner_id` int(11) NOT NULL,
`sales_partner_structure` int(11) DEFAULT NULL,
`active` tinyint(1) NOT NULL,
`blocked` tinyint(1) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
I can't get my problem, does somebody have a clue? Thanks in advance!
Thanks to Paul Spiegel for his reminding that I can only set FKs to the indexed fields. After another review I noticed that my referenced field was not indexed, that solved my problem.

MySQL foreign key contraint allow nulls not working

I can't seem to figure out why my foreign key constraints aren't working. Here's my table schema:
CREATE TABLE `templates_textboxes` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`template_id` int(10) unsigned DEFAULT NULL,
`textbox_id` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `templates_textboxes_to_templates_idx` (`template_id`),
KEY `templates_textboxes_to_textboxes_idx` (`textbox_id`),
CONSTRAINT `templates_textboxes_to_templates` FOREIGN KEY (`template_id`) REFERENCES `templates` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1$$
CREATE TABLE `textboxes` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`content` text NOT NULL,
`columns` tinyint(1) unsigned NOT NULL DEFAULT '1',
`width` int(5) unsigned NOT NULL DEFAULT '0',
`height` int(5) unsigned NOT NULL DEFAULT '0',
`x` int(5) unsigned NOT NULL DEFAULT '0',
`y` int(5) unsigned NOT NULL DEFAULT '0',
`z` int(5) unsigned NOT NULL DEFAULT '500',
PRIMARY KEY (`id`),
CONSTRAINT `textboxes_to_templates_textboxes` FOREIGN KEY (`id`) REFERENCES `templates_textboxes` (`textbox_id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8$$
When I create a textbox in PHP, first I insert into textboxes to get the ID then insert a row in the match table templates_textboxes with the template id and new textbox id. I've read every post I can find on here about foreign keys allowing nulls and all it says to do is to set the foreign key column (templates_textboxes.textbox_id) to allow nulls. I tried that and when I try to insert into textboxes I get the following error:
Error Number: 1452
Cannot add or update a child row: a foreign key constraint fails (`pitchperfect`.`textboxes`, CONSTRAINT `textboxes_to_templates_textboxes` FOREIGN KEY (`id`) REFERENCES `templates_textboxes` (`textbox_id`) ON DELETE CASCADE ON UPDATE NO ACTION)INSERT INTO `textboxes` (`content`, `columns`, `width`, `height`, `x`, `y`, `z`) VALUES ('', '1', '400', '300', '133', '93', '500')
What I'm trying to accomplish is have cascade deletes chain from themes, to templates and their assets (templates_textboxes -> textboxes).
Thanks!
Since textboxes.id is not yet defined and is AUTO_INCREMENT, that value must first exist in templates_textboxes.textbox_id. This is why the constraint is failing.

MYSQL: Cannot add or update a child row: a foreign key constraint fails

I am getting the error:
Cannot add or update a child row: a foreign key constraint fails (mydb/requests, CONSTRAINT requests_ibfk_5 FOREIGN KEY (fixture_id) REFERENCES fixtures (fix_id) ON UPDATE CASCADE ON DELETE CASCADE)
I have the following table structure:
CREATE TABLE IF NOT EXISTS `requests` (
`request_id` int(11) unsigned NOT NULL auto_increment,
`fixture_id` int(11) unsigned NOT NULL,
`user_id` int(11) unsigned NOT NULL,
`date_added` datetime NOT NULL,
`date_modified` datetime default NULL,
PRIMARY KEY (`request_id`),
UNIQUE KEY `fixture_id_2` (`fixture_id`,`user_id`),
KEY `user_id` (`user_id`),
KEY `date_added` (`date_added`),
KEY `fixture_id` (`fixture_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=17 ;
CREATE TABLE IF NOT EXISTS `fixtures` (
`id` int(11) unsigned NOT NULL auto_increment,
`fix_id` int(11) unsigned NOT NULL default '0',
`fixture_date` date default NULL,
`kickoff` time default NULL,
`venue` varchar(35) default NULL,
`home_score` tinyint(4) default NULL,
`away_score` tinyint(4) default NULL,
`date_added` datetime default NULL,
`date_modified` datetime default NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `fix_id` (`fix_id`),
KEY `fixture_date` (`fixture_date`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=383 ;
ALTER TABLE `requests`
ADD CONSTRAINT `requests_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`) ON DELETE CASCADE,
ADD CONSTRAINT `requests_ibfk_5` FOREIGN KEY (`fixture_id`) REFERENCES `fixtures` (`fix_id`) ON DELETE CASCADE ON UPDATE CASCADE;
If I update a record on the fix_id field the parent table (fixtures), that has a shared id (fixture_id) in the child table (requests) I get the above error.
I cannot see why this integrity constraint is failing. Both tables already have the correct data it should cascade through?
Any help greatly appreciated.
This was all my own error. I had two foreign constraints on the same field in reality. I just needed to take one off.
This error occurs due to the reference of other table, in both tables same id's/data should exist. If not please use where conditions to remove not existing data.
example
update tablename a set = 'field' (select field from othertable b) where a.data = b.data;