Foreign Keys on two different schemas mysql - mysql

I have two tables on distinct schemas
db1.invoice
CREATE TABLE IF NOT EXISTS db1.`invoice` (
`invoice_id` int(11) NOT NULL AUTO_INCREMENT,
`qsales_sale_id` int(11) DEFAULT NULL,
`invoice_id_from_dosage_id` int(11) NOT NULL,
`number` int(11) DEFAULT NULL,
`enterprise_name` varchar(100) DEFAULT NULL,
`subsidiary_name` varchar(100) DEFAULT NULL,
`subsidiary_address` varchar(200) DEFAULT NULL,
`subsidiary_phone` varchar(40) DEFAULT NULL,
`client_name` varchar(200) DEFAULT NULL,
`nit` bigint(20) DEFAULT NULL,
`was_paid` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`invoice_id`),
KEY `fk_invoice_qsales_sale1_idx` (`qsales_sale_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=457 ;
bd2.qsale_sale
CREATE TABLE IF NOT EXISTS db2.qsales_sale (
`qsales_sale_id` int(11) NOT NULL AUTO_INCREMENT,
`qsales_order_type_id` int(11) NOT NULL,
`client_id` int(11) NOT NULL,
`total_cost` decimal(10,2) DEFAULT NULL,
`currency` varchar(45) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`has_discount` tinyint(1) DEFAULT NULL,
`created_by` int(11) NOT NULL,
`is_wholesaler` tinyint(1) NOT NULL DEFAULT '0',
`payment_type` varchar(65) DEFAULT NULL,
PRIMARY KEY (`qsales_sale_id`),
KEY `fk_qsales_sale_qsales_order_type1_idx` (`qsales_order_type_id`),
KEY `fk_qsales_sale_client1_idx` (`client_id`),
KEY `fk_qsales_sale_employee1_idx` (`created_by`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=51 ;
then i want to add a foreign key
I try:
1.
alter table bd1.invoice
add foreign key fk_invoice_qsales_sale1(qsales_sale_id)
references db2.qsales_sale (qsales_sale_id)
on delete cascade
on update cascade;
ALTER TABLE db1.invoice
ADD CONSTRAINT fk_invoice_qsales_sale1 FOREIGN KEY (qsales_sale_id)
REFERENCES db2.qsales_sale (qsales_sale_id) ON DELETE NO ACTION ON UPDATE NO ACTION;
But i have this error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`qfix`.`#sql-a28_5`, CONSTRAINT `#sql-a28_5_ibfk_1` FOREIGN KEY (`qsales_sale_id`) REFERENCES `qsales`.`qsales_sale` (`qsales_sale_id`) ON DELETE CASCADE ON UPDATE CASCADE)
0.625 sec

Related

In my MySQL query I'm getting "Cannot add foreign key constraint error", what could be the reason?

In my MySQL query I'm getting this error:
Cannot add foreign key constraint error
What could be the reason?
CREATE TABLE `social_account` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`type` enum('facebook','Twitter') DEFAULT NULL,
`pageid` varchar(200) DEFAULT NULL,
`accesstoken` varchar(200) DEFAULT NULL,
`pagename` varchar(200) DEFAULT NULL,
`ProfilePicture` varchar(200) DEFAULT NULL,
`page_url` varchar(300) DEFAULT NULL,
`accesstokensecreat` varchar(200) DEFAULT NULL,
`is_expire` int(1) DEFAULT '0',
PRIMARY KEY (`ID`),
KEY `fk_user_social_account` (`user_id`),
CONSTRAINT `fk_user_social_account` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4
may be Your Foreign key datatype is not matched with the referring table

Unable to update a child row in my Database (MySQL)

Using the following SQL statement..
INSERT INTO `debates` (`id`, `unit_id`, `starter_pack_id`, `academic_id`, `title`, `date_due`, `date_created`, `date_modified`) VALUES
(1, 1, 1, 5, 'On Campus', '2016-12-25 00:00:00', now(), NULL),
(2, 1, 1, 5, 'Off Campus', '2016-12-25 00:00:00', now(), NULL);
Results in the following error being output..
#1452 - Cannot add or update a child row: a foreign key constraint fails (`my_database`.`debates`, CONSTRAINT `fk_debates_starter_pack_id` FOREIGN KEY (`starter_pack_id`) REFERENCES `debate_starter_packs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
Why am I unable to update this table?
Please Note : Below are all the tables associated with this SQL statement. There are currently no tables contain any data in the database.
Debates:
CREATE TABLE `debates`(
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`unit_id` INT(11) UNSIGNED NOT NULL,
`starter_pack_id` TINYINT(3) UNSIGNED NOT NULL,
`academic_id` INT(11) UNSIGNED NOT NULL,
`title` VARCHAR(255) NOT NULL,
`date_due` DATETIME NOT NULL,
`date_created` DATETIME NOT NULL,
`date_modified` DATETIME DEFAULT NULL,
CONSTRAINT `pk_debates_id` PRIMARY KEY(`id`),
CONSTRAINT `fk_debates_starter_pack_id` FOREIGN KEY(`starter_pack_id`) REFERENCES `debate_starter_packs`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_debates_unit_id` FOREIGN KEY(`unit_id`) REFERENCES `units`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_debates_user_role_id` FOREIGN KEY(`academic_id`) REFERENCES `user_roles`(`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE = InnoDB DEFAULT CHARSET = utf8;
Units (Unit_ID Reference):
CREATE TABLE `units` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`academic_id` int(11) UNSIGNED NOT NULL,
`unit_code` varchar(6) NOT NULL,
`title` varchar(100) DEFAULT NULL,
`date_added` datetime NOT NULL,
`date_modified` datetime DEFAULT NULL,
CONSTRAINT `pk_units_id` PRIMARY KEY(`id`),
CONSTRAINT `fk_units_academic_id` FOREIGN KEY (`academic_id`) REFERENCES `user_roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Starter Packs (Starter_Pack_ID Reference):
CREATE TABLE `debate_starter_packs` (
`id` tinyint(3) UNSIGNED NOT NULL AUTO_INCREMENT,
`academic_id` int(11) UNSIGNED NOT NULL,
`title` varchar(100) NOT NULL,
`description` text NOT NULL,
`date_created` datetime NOT NULL,
`date_modified` datetime DEFAULT NULL,
CONSTRAINT `pk_debate_starter_packs_id` PRIMARY KEY(`id`),
CONSTRAINT `fk_debate_starter_packs_user_role_id` FOREIGN KEY (`academic_id`) REFERENCES `user_roles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Users (Academic_ID Reference):
CREATE TABLE `users` (
`id` int(11) UNSIGNED NOT NULL,
`username` varchar(100) DEFAULT NULL,
`first_name` varchar(50) DEFAULT NULL,
`last_name` varchar(50) DEFAULT NULL,
`email` varchar(100) NOT NULL,
`password` varchar(255) NOT NULL,
`salt` varchar(255) DEFAULT NULL,
`organisation` varchar(100) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
`date_created` datetime NOT NULL,
`date_last_login` datetime DEFAULT NULL,
`remember_code` varchar(40) DEFAULT NULL,
`active` tinyint(1) UNSIGNED NOT NULL,
CONSTRAINT `pk_users_id` PRIMARY KEY(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Do you have the record id='1' in the table debate_starter_packs ?
The table debates have a foreign key reference id of table debate_starter_packs.
CONSTRAINT `fk_debates_starter_pack_id` FOREIGN KEY(`starter_pack_id`) REFERENCES `debate_starter_packs`(`id`) ON DELETE CASCADE ON UPDATE CASCADE,
You should insert the record id='1' to the table debate_starter_packs first.

MySQL Workbench error 1452

I've trying to create a foreign key from a table to another, using the tools that MySQL Workbench provides, but all that I get is this error:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`mediacom`.`#sql-758_4`, CONSTRAINT `med_agente_ibfk_1` FOREIGN KEY (`id_agenzia`) REFERENCES `med_agenzia` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
SQL Statement:
ALTER TABLE `mediacom`.`med_agente`
ADD CONSTRAINT `med_agente_ibfk_1`
FOREIGN KEY (`id_agenzia`)
REFERENCES `mediacom`.`med_agenzia` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
The thing that confuses me the most is the line mediacom.#sql-758_4, since the real query that I use is :
ALTER TABLE `mediacom`.`med_agente`
ADD INDEX `med_agente_ibfk_1_idx` (`id_agenzia` ASC) COMMENT '';
ALTER TABLE `mediacom`.`med_agente`
ADD CONSTRAINT `med_agente_ibfk_1`
FOREIGN KEY (`id_agenzia`)
REFERENCES `mediacom`.`med_agenzia` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
The index is inserted fine but the rest is ignored, why?
This is the med_agente table
CREATE TABLE `med_agente` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nome` varchar(225) DEFAULT NULL,
`cognome` varchar(225) DEFAULT NULL,
`disabilitato` tinyint(1) DEFAULT NULL,
`mod_time` datetime DEFAULT NULL,
`mod_user` varchar(255) DEFAULT NULL,
`codmobile` decimal(13,0) DEFAULT NULL,
`codfisso` decimal(13,0) DEFAULT NULL,
`id_agenzia` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `med_agente_ibfk_1_idx` (`id_agenzia`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
And this is med_agenzia
CREATE TABLE `med_agenzia` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ragSociale` varchar(255) NOT NULL,
`descrizione` varchar(255) DEFAULT NULL,
`indirizzo` varchar(255) DEFAULT NULL,
`citta` varchar(255) DEFAULT NULL,
`CAP` int(11) DEFAULT NULL,
`provincia` varchar(255) DEFAULT NULL,
`tel` int(11) DEFAULT NULL,
`mail` varchar(255) DEFAULT NULL,
`codFiscale` varchar(255) DEFAULT NULL,
`pIVA` varchar(255) DEFAULT NULL,
`id_azsuper` int(11) DEFAULT NULL,
`disabilitato` tinyint(1) DEFAULT NULL,
`mod_time` datetime DEFAULT NULL,
`mod_user` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
where's the problem???
Before you run your query
Run this :
SET FOREIGN_KEY_CHECKS=0;
Then set it to 1
SET FOREIGN_KEY_CHECKS=1;
after you run your Alter query.

Cannot delete foreign key constraint fails

When I try to delete the question from the test, the sql show :
`Cannot delete or update a parent row: a foreign key constraint fails (`oes`.`studentquestion`,
CONSTRAINT `studentquestion_ibfk_2` FOREIGN KEY (`testid`, `qnid`) REFERENCES `question`
(`testid`, `qnid`))`
Here will be my table:
student table
CREATE TABLE `student` (
`stdid` bigint(20) NOT NULL,
`subid` int(11) NOT NULL,
`stdname` varchar(40) default NULL,
`stdpassword` varchar(40) default NULL,
`emailid` varchar(40) default NULL,
`contactno` varchar(20) default NULL,
`address` varchar(40) default NULL,
`city` varchar(40) default NULL,
`pincode` varchar(20) default NULL,
PRIMARY KEY (`stdid`),
UNIQUE KEY `stdname` (`stdname`),
UNIQUE KEY `emailid` (`emailid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
studentquestion table
CREATE TABLE `studentquestion` (
`stdid` bigint(20) NOT NULL default '0',
`testid` bigint(20) NOT NULL default '0',
`qnid` int(11) NOT NULL default '0',
`answered` enum('answered','unanswered','review') DEFAULT NULL,
`stdanswer` enum('optiona','optionb','optionc','optiond') DEFAULT NULL,
PRIMARY KEY (`stdid`,`testid`,`qnid`),
KEY `testid` (`testid`,`qnid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
studenttest table
`stdid` bigint(20) NOT NULL default '0',
`testid` bigint(20) NOT NULL default '0',
`starttime` timestamp NOT NULL default CURRENT_TIMESTAMP,
`endtime` timestamp NOT NULL default '0000-00-00 00:00:00',
`correctlyanswered` int(11) default NULL,
`status` enum('over','inprogress') default NULL,
PRIMARY KEY (`stdid`,`testid`),
KEY `testid` (`testid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
question table
CREATE TABLE `question` (
`testid` bigint(20) NOT NULL default '0',
`qnid` int(11) NOT NULL default '0',
`question` varchar(500) default NULL,
`optiona` varchar(100) DEFAULT NULL,
`optionb` varchar(100) DEFAULT NULL,
`optionc` varchar(100) DEFAULT NULL,
`optiond` varchar(100) DEFAULT NULL,
`correctanswer` enum ('optiona','optionb','optionc','optiond') DEFAULT NULL,
`marks` int(11) DEFAULT NULL,
PRIMARY KEY (`testid`,`qnid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
test table
CREATE TABLE `test` (
`testid` bigint(20) NOT NULL,
`testname` varchar(30) NOT NULL,
`testdesc` varchar(100) default NULL,
`testdate` date default NULL,
`testtime` time default NULL,
`subid` int(11) default NULL,
`testfrom` timestamp NOT NULL default CURRENT_TIMESTAMP,
`testto` timestamp NOT NULL default '0000-00-00 00:00:00',
`duration` int(11) default NULL,
`totalquestions` int(11) default NULL,
`attemptedstudents` bigint(20) DEFAULT NULL,
`testcode` varchar(40) NOT NULL,
`tcid` bigint(20) default NULL,
`minimunscore` int(11) NOT NULL,
PRIMARY KEY (`testid`),
UNIQUE KEY `testname` (`testname`),
KEY `test_fk1` (`subid`),
KEY `test_fk2` (`tcid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
subject table
CREATE TABLE `subject` (
`subid` int(11) NOT NULL,
`subname` varchar(40) default NULL,
`subdesc` varchar(100) default NULL,
`tcid` bigint(20) default NULL,
PRIMARY KEY (`subid`),
UNIQUE KEY `subname` (`subname`),
KEY `subject_fk1` (`tcid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `studentquestion`
ADD CONSTRAINT `studentquestion_ibfk_1` FOREIGN KEY (`stdid`) REFERENCES `student`
(`stdid`),
ADD CONSTRAINT `studentquestion_ibfk_2` FOREIGN KEY (`testid`, `qnid`) REFERENCES `question`
(`testid`, `qnid`);
ALTER TABLE `studenttest`
ADD CONSTRAINT `studenttest_ibfk_1` FOREIGN KEY (`stdid`) REFERENCES `student` (`stdid`),
ADD CONSTRAINT `studenttest_ibfk_2` FOREIGN KEY (`testid`) REFERENCES `test` (`testid`);
ALTER TABLE `question`
ADD CONSTRAINT `question_ibfk_1` FOREIGN KEY (`testid`) REFERENCES `test` (`testid`);
ALTER TABLE `test`
ADD CONSTRAINT `test_fk1` FOREIGN KEY (`subid`) REFERENCES `subject` (`subid`),
ADD CONSTRAINT `test_fk2` FOREIGN KEY (`tcid`) REFERENCES `testconductor` (`tcid`);
ALTER TABLE `subject`
ADD CONSTRAINT `subject_fk1` FOREIGN KEY (`tcid`) REFERENCES `testconductor` (`tcid`);
INSERT INTO `adminlogin` VALUES ('001','root','root');
INSERT INTO `studenttest` (`stdid`, `testid`, `starttime`, `endtime`, `correctlyanswered`,
`status`) VALUES
(1, 1, '2014-10-15 09:11:24', '2014-10-15 09:21:24', 0, 'over');
INSERT INTO `subject` (`subid`, `subname`, `subdesc`, `tcid`) VALUES
(1, 'fref', 'few', NULL);
INSERT INTO `test` (`testid`, `testname`, `testdesc`, `testdate`, `testtime`, `subid`,
`testfrom`, `testto`, `duration`, `totalquestions`, `attemptedstudents`, `testcode`, `tcid`)
VALUES
(1, 'gregre', 'greger', '2014-10-15', '17:08:16', 1, '2014-10-15 03:08:16', '2014-10-16
15:59:59', 10, 2, 0, '.ȁ', NULL);
When the student has complete the test, then the question will not be able to delete. Neither the test or subject.
It is because the studentquestion table will be left with a foreign key that points to a non existent record. You'll either need to remove rows which have a foreign key to the record you want to delete or, alternatively set up CASCADE rules so that when parent rows are deleted action can be taken.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row on CONSTRAINT `fk_users_has_ratings_businesses1

I'm getting this error when i try to insert new ratings
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`yuldi`.`users_ratings`, CONSTRAINT `fk_users_has_ratings_businesses1` FOREIGN KEY (`business_id`) REFERENCES `businesses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
below database table structure with some foreign keys. i'm confused with adding multiple primary and foreign keys. please help me to sort out this issue
CREATE TABLE IF NOT EXISTS `yuldi`.`businesses` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`state` VARCHAR(100) NOT NULL,
`slug` VARCHAR(250) NOT NULL,
`city` VARCHAR(100) NOT NULL,
`suburb` VARCHAR(100) NOT NULL,
`business_name` VARCHAR(100) NOT NULL,
`business_address` VARCHAR(250) NOT NULL,
`business_postal` VARCHAR(10) NOT NULL,
`business_postal_id` INT(11) NOT NULL,
`business_phone` VARCHAR(50) NOT NULL,
`business_phone1` VARCHAR(50) NOT NULL,
`business_phone2` VARCHAR(50) NOT NULL,
`business_email` VARCHAR(100) NOT NULL,
`business_website` VARCHAR(200) NOT NULL,
`business_details` VARCHAR(5000) NOT NULL,
`business_openinghours` VARCHAR(200) NOT NULL,
`business_service` VARCHAR(200) NOT NULL,
`business_addtionalinfo` VARCHAR(200) NOT NULL,
`business_lat` FLOAT(10,6) NOT NULL,
`business_lng` FLOAT(10,6) NOT NULL,
`identity` VARCHAR(100) NOT NULL,
`status` INT(11) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 232
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`ratings` (
`id` VARCHAR(36) NOT NULL,
`model` VARCHAR(255) NOT NULL,
`value` FLOAT(8,4) NULL DEFAULT '0.0000',
`comment` TEXT NULL DEFAULT NULL,
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `UNIQUE_RATING` (`model` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_email` VARCHAR(255) NULL DEFAULT NULL,
`user_password` CHAR(100) NULL DEFAULT NULL,
`user_name` VARCHAR(255) NULL DEFAULT NULL,
`user_code` VARCHAR(255) NULL DEFAULT NULL,
`user_status` TINYINT(4) NULL DEFAULT '0',
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
`ip_address` VARCHAR(15) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 14
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`users_ratings` (
`user_id` INT(11) NOT NULL,
`rating_id` VARCHAR(36) NOT NULL,
`business_id` INT(11) NOT NULL,
PRIMARY KEY (`user_id`, `rating_id`, `business_id`),
INDEX `fk_users_has_ratings_ratings1_idx` (`rating_id` ASC),
INDEX `fk_users_has_ratings_users1_idx` (`user_id` ASC),
INDEX `fk_users_has_ratings_businesses1_idx` (`business_id` ASC),
CONSTRAINT `fk_users_has_ratings_businesses1`
FOREIGN KEY (`business_id`)
REFERENCES `yuldi`.`businesses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_users_has_ratings_ratings1`
FOREIGN KEY (`rating_id`)
REFERENCES `yuldi`.`ratings` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_users_has_ratings_users1`
FOREIGN KEY (`user_id`)
REFERENCES `yuldi`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
The problem is coming from this:
CONSTRAINT `fk_users_has_ratings_businesses1`
FOREIGN KEY (`business_id`)
REFERENCES `yuldi`.`businesses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
The record you're trying to insert / update - probably user_ratings - is foreign keyed to the businesses table; you can't create a user_ratings record without a business_id, and that business_id must actually exist as an id in the businesses table.