MySQL Foreign keys - Error 150 while creating tables - mysql

I have written some SQL code to create five tables with several relations(foreign keys).
The first foreign key relation works fine, the tables are created without any errors, but when I try to create gasten_url_toegangscodes I get the following error:
#1005 - Can't create table 'dbname.gasten_url_toegangscodes' (errno: 150).
I've read the docs about foreign keys and I still can't find the problem.. The most strange thing about this is that it works in the first three tables..
Can anyone help me please?
My full SQL code is:
CREATE TABLE IF NOT EXISTS `groepen` (
`id` tinyint(3) NOT NULL AUTO_INCREMENT,
`naam` varchar(50) NOT NULL DEFAULT '',
`status` tinyint(1) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `gasten` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`bedrijf` varchar(100) NOT NULL DEFAULT '',
`uniek` varchar(64) NOT NULL,
`groepid` tinyint(3) NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (groepid) REFERENCES `groepen` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `passen` (
`id` tinyint(3) NOT NULL AUTO_INCREMENT,
`naam` varchar(30) NOT NULL DEFAULT '',
`color` varchar(7) NOT NULL DEFAULT '#FFFFFF',
`bekend` tinyint(1) NOT NULL DEFAULT '0',
`welkom` tinyint(1) NOT NULL DEFAULT '0',
`aantal` tinyint(1) NOT NULL DEFAULT '0',
`nummer` int(11) NOT NULL DEFAULT '0',
`begrens` tinyint(1) NOT NULL DEFAULT '0',
`status` tinyint(1) NOT NULL DEFAULT '1',
`priority` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `naam` (`naam`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `gasten_url_toegangscodes` (
`uniek` varchar(64) NOT NULL,
`unieke_url_code` char(64) NOT NULL,
`salt` char(16) NOT NULL,
FOREIGN KEY (uniek) REFERENCES `gasten` (`uniek`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `gasten_tickets` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`pas_id` tinyint(3) NOT NULL,
`uniek` varchar(64) NOT NULL,
`barcode` char(16) NOT NULL,
`secret_key` char(32) NOT NULL,
`download_count` int(11) NOT NULL DEFAULT '0',
`last_download_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`scanned` enum('N','Y') NOT NULL,
`scanned_datetime` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
FOREIGN KEY (uniek) REFERENCES `gasten` (`uniek`) ON DELETE CASCADE ON UPDATE NO ACTION,
FOREIGN KEY (pas_id) REFERENCES `passen` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB;
Thanks in advance!

Create an index on gasten.uniek
CREATE TABLE IF NOT EXISTS `gasten` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`bedrijf` varchar(100) NOT NULL DEFAULT '',
`uniek` varchar(64) NOT NULL,
`groepid` tinyint(3) NOT NULL,
PRIMARY KEY (`id`),
INDEX `idx_uniek` (`uniek`),
FOREIGN KEY (groepid) REFERENCES `groepen` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB;
And set the charset of the FK in gasten_url_toegangscodes the same as that of the related column in gasten.
Assuming gasten is UTF-8:
CREATE TABLE IF NOT EXISTS `gasten_url_toegangscodes` (
/* use same charset for this column */
`uniek` varchar(64) NOT NULL CHARSET UTF-8,
`unieke_url_code` char(64) NOT NULL,
`salt` char(16) NOT NULL,
FOREIGN KEY (uniek) REFERENCES `gasten` (`uniek`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Related

Foreign Keys on two different schemas 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

#1452 - Cannot add or update a child row: a foreign key constraint fails ... Jutts

I have created tables in MySQL Workbench as shown below :
Categories Table
CREATE TABLE IF NOT EXISTS `categories` (
`categoryId` int(11) primary key auto_incremnt NOT NULL,
`categoryName` varchar(200) DEFAULT NULL,
`categoryDescription` varchar(200) DEFAULT NULL,
`categoryPicture` varchar(100) DEFAULT NULL,
`PostDate` varchar(255) NOT NULL,
`status` varchar(10) NOT NULL DEFAULT '1',
`LastInsertID` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=45 ;
Products Table
CREATE TABLE IF NOT EXISTS `products` (
`proId` int(11) NOT NULL,
CONSTRAINT `categoryId` FOREIGN KEY (`categoryId`) REFERENCES `categories` (`categoryId`) ,
`proName` varchar(100) DEFAULT NULL,
`proPath` varchar(90) DEFAULT NULL,
`proPrice` float DEFAULT NULL,
`proQuantity` decimal(38,0) DEFAULT NULL,
`proImage` varchar(100) DEFAULT NULL,
`PostDate` varchar(50) NOT NULL,
`status` int(11) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
I'm having a bit of a strange problem, I'm trying to add a foreign key
to one table that references another, but it is failing for some
reason. With my limited knowledge of MySQL, the only thing that could
possibly be suspect is that there is a foreign key on a different
table referencing the one I am trying to reference.
Please help me out as soon as possible .
Thanks in advance
You should create the categoryId column before assigning it in a foreign key,
categoryId int(11) NOT NULL,
CREATE TABLE IF NOT EXISTS `products` (
`proId` INT(11) NOT NULL,
`categoryId` INT ,
`proName` VARCHAR(100) DEFAULT NULL,
`proPath` VARCHAR(90) DEFAULT NULL,
`proPrice` FLOAT DEFAULT NULL,
`proQuantity` DECIMAL(38,0) DEFAULT NULL,
`proImage` VARCHAR(100) DEFAULT NULL,
`PostDate` VARCHAR(50) NOT NULL,
`status` INT(11) NOT NULL DEFAULT '1',
FOREIGN KEY (`categoryId`) REFERENCES `categories` (`categoryId`)
) ENGINE=INNODB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

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.

mysql create table with foreign keys failing

I am trying to create a tables in a db that have foreign keys. what am i missing?
CREATE TABLE `users` (
`id` bigint(10) NOT NULL AUTO_INCREMENT,
`userName` varchar(24) NOT NULL DEFAULT '',
`password` varchar(32) NOT NULL DEFAULT '',
`firstName` varchar(32) NOT NULL DEFAULT '',
`lastName` varchar(32) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
CREATE TABLE `topLevelPermissions` (
`id` bigint(10) NOT NULL AUTO_INCREMENT,
`userId` bigint(10) NOT NULL DEFAULT '0',
`user` char(1) NOT NULL DEFAULT '0',
`group` char(1) NOT NULL DEFAULT '0',
`someField` char(1) NOT NULL DEFAULT '0',
`someOtherField` char(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
FOREIGN KEY (`userId`) REFERENCES users (`id`) ON DELETE CASCADE
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
and i see nothing related to foreign keys. in fact when i
show create table topLevelPermissions;
i see
CREATE TABLE `topLevelPermissions` (
`id` bigint(10) NOT NULL AUTO_INCREMENT,
`userId` bigint(10) NOT NULL DEFAULT '0',
`user` char(1) NOT NULL DEFAULT '0',
`group` char(1) NOT NULL DEFAULT '0',
`someField` char(1) NOT NULL DEFAULT '0',
`someOtherField` char(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `userId` (`userId`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
Innodb only supports foreign key constraints. So switch to Innodb if you want to utilize foreign key constraints.

#1005 - Can't create table errno: 150 Magento

I am trying to create a new table for magento and I am trying to reference existing magento tables. From what I googled, the problem that I am getting can be 1 of the 2 issues.
The FK must have a index
The PK must exist before the FK can reference
In both cases, I believe I did both of these correctly. Below is existing table schemas
ALREADY EXISTING TABLES BEING REFERENCED
CREATE TABLE IF NOT EXISTS `core_store` (
`store_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(32) NOT NULL DEFAULT '',
`website_id` smallint(5) unsigned DEFAULT '0',
`group_id` smallint(5) unsigned NOT NULL DEFAULT '0',
`name` varchar(255) NOT NULL,
`sort_order` smallint(5) unsigned NOT NULL DEFAULT '0',
`is_active` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`store_id`),
UNIQUE KEY `code` (`code`),
KEY `FK_STORE_WEBSITE` (`website_id`),
KEY `is_active` (`is_active`,`sort_order`),
KEY `FK_STORE_GROUP` (`group_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Stores' AUTO_INCREMENT=9 ;
CREATE TABLE IF NOT EXISTS `admin_user` (
`user_id` mediumint(9) unsigned NOT NULL AUTO_INCREMENT,
`firstname` varchar(32) NOT NULL DEFAULT '',
`lastname` varchar(32) NOT NULL DEFAULT '',
`email` varchar(128) NOT NULL DEFAULT '',
`username` varchar(40) NOT NULL DEFAULT '',
`password` varchar(100) NOT NULL DEFAULT '',
`created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`modified` datetime DEFAULT NULL,
`logdate` datetime DEFAULT NULL,
`lognum` smallint(5) unsigned NOT NULL DEFAULT '0',
`reload_acl_flag` tinyint(1) NOT NULL DEFAULT '0',
`is_active` tinyint(1) NOT NULL DEFAULT '1',
`extra` text,
`failures_num` smallint(6) NOT NULL DEFAULT '0',
`first_failure` datetime DEFAULT NULL,
`lock_expires` datetime DEFAULT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `UNQ_ADMIN_USER_USERNAME` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Users' AUTO_INCREMENT=25 ;
Table I am trying to create
CREATE TABLE `oro_dashboard`
( `id` int unsigned NOT NULL,
`name` varchar(255) NOT NULL default '',
`description` varchar(64) NOT NULL default '',
`created_by` int unsigned NOT NULL default '0',
`created_at` date,
`layout` varchar(255) NOT NULL default '',
`default_store_id` int,
PRIMARY KEY (`id`),
KEY `IDX_ORO_DASHBOARD_CREATED_BY` (`created_by`),
CONSTRAINT `FK_ORO_DASHBOARD_CREATED_BY_ADMIN_USER_USER_ID` FOREIGN KEY (`created_by`) REFERENCES `admin_user` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_ORO_DASHBOARD_DEFAULT_STORE_ID_CORE_STORE_STORE_ID` FOREIGN KEY (`default_store_id`) REFERENCES `core_store` (`store_id`) ON DELETE SET NULL ON UPDATE CASCADE )
ENGINE=INNODB charset=utf8 COLLATE=utf8_unicode_ci
In magento, I found there is in deed a table called admin_user that does have a column called user_id. There is a core_store table that does have a column called store_id. and both my columns have INDEXES made.
Does anyone have any clue what the issue maybe ? Below is my error message
#1005 - Can't create table 'db.oro_dashboard' (errno: 150)
It is necessary to have data type to be same for the foreign key and its corresponding parent key. The data type is different of the foreign key and its referencing parent key in your table that is why it is giving an error.
created by is int unsigned while userid is medium int in parent table
same is problem in the second foreign key
reference http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
When defining foreign keys, the data type must be the same.
You are defining core_store.store_id as smallint(5) unsigned and so the referencing column must be the same: oro_dashboard.default_store_id.
Do also with oro_dashboard.created_by
Final oro_dashboard CREATE TABLE query,
CREATE TABLE `oro_dashboard`
( `id` int unsigned NOT NULL,
`name` varchar(255) NOT NULL default '',
`description` varchar(64) NOT NULL default '',
`created_by` mediumint(9) unsigned NOT NULL default '0',
`created_at` date,
`layout` varchar(255) NOT NULL default '',
`default_store_id` smallint(5) unsigned,
PRIMARY KEY (`id`),
KEY `IDX_ORO_DASHBOARD_CREATED_BY` (`created_by`) ,
CONSTRAINT `FK_ORO_DASHBOARD_CREATED_BY_ADMIN_USER_USER_ID`
FOREIGN KEY (`created_by`)
REFERENCES `admin_user` (`user_id`)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `FK_ORO_DASHBOARD_DEFAULT_STORE_ID_CORE_STORE_STORE_ID`
FOREIGN KEY (`default_store_id`)
REFERENCES `core_store` (`store_id`)
ON DELETE SET NULL ON UPDATE CASCADE
)
SQLFIddle Demo
It appears that the column definition for default_store_id does not match core_store.store_id. it should be smallint(5) unsigned in your table. created_by has the same problem, although it did not prevent the table from being created