Error Code: 1005 - Can't create table (errno: 150) - sql

I apologize for asking question related to this topic, I know this topic has been discussed on few other posts and its kind of a duplicate but the posts I been through did not help me in fixing my issue.
I have the following SQL code to add two tables:
CREATE TABLE IF NOT EXISTS `opa`.`iddocumenttype`(
`iddocumenttypeid` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
PRIMARY KEY(`iddocumenttypeid`),
KEY (`iddocumenttypeid`)
) ENGINE=INNODB CHARSET=utf8;
and
CREATE TABLE IF NOT EXISTS `opa`.`identificationdocumentdetails`(
`identificationdocumentdetailsid` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`IDdocumenttypeid` INT(11) UNSIGNED NOT NULL,
`IDdocumentnumber` VARCHAR(128),
`name` VARCHAR(200) COMMENT 'Exact name as on idDoc?',
`dateofissue` DATE CHECK (dateofissue < CURRENT_DATE()),
`placeofissue` VARCHAR(128),
`validtill` DATE CHECK (validtill > CURRENT_DATE()),
PRIMARY KEY (`identificationdocumentdetailsid`),
CONSTRAINT `FK_identificationdocumentdetails_iddocumenttype` FOREIGN KEY (`IDdocumenttypeid`) REFERENCES `opa`.`iddocumenttype`(`iddocumenttypeid`)) ENGINE=INNODB CHARSET=utf8;
Now, when I run the query to create the second table which is identificationdocumentdetails , I get the following error:
Error Code: 1005
Can't create table 'opa.identificationdocumentdetails' (errno: 150)
I dont understand why its happening, I am sure some thing has to do with CONSTRAINT line because when I remove this line:
CONSTRAINT `FK_identificationdocumentdetails_iddocumenttype` FOREIGN KEY (`IDdocumenttypeid`) REFERENCES `opa`.`iddocumenttype`(`iddocumenttypeid`)
the store procedure works fine, but I think I am missing whats going wrong here, Can some one please point out to me what am I not seeing here....

`IDdocumenttypeid` INT(11)
in identificationdocumentdetails table need to be the exactly same type as the column referenced,which is
`iddocumenttypeid` INT(11) UNSIGNED NOT NULL
http://sqlfiddle.com/#!9/66b6d

Related

Error creating foreign key on <table>(check data types)

Error creating foreign key on local_fees (check data types)
I already check my datatypes in both table manage_fees and fees table
Already set fees pk into unsgined same as the manage_fee im still getting the error message about datatypes
error that im getting whenever i set on delete null
ALTER TABLE manage_fees ADD CONSTRAINT fk_fees FOREIGN KEY (local_fees) REFERENCES fees(id) ON DELETE SET NULL ON UPDATE RESTRICT;
aside from that whenever i set on delete restrict it works without showing error message.
ALTER TABLE manage_fees ADD CONSTRAINT fk_fees FOREIGN KEY (local_fees) REFERENCES fees(id) ON DELETE RESTRICT ON UPDATE RESTRICT;
Anyone can help me with my problem?
You cannot apply ON DELETE SET NULL for local_fees because it is not NULLABLE.
If you need to default it to NULL, you should make it nullable:
CREATE TABLE `manage_fees` (
`id` int(11) NOT NULL,
`school_year` varchar(255) NOT NULL,
`year_lvl` varchar(255) NOT NULL,
`course` varchar(255) NOT NULL,
`semester` varchar(255) NOT NULL,
`local_fees` int(11) NULL,
`time_created` datetime NOT NULL DEFAULT current_timestamp()
)

Creating relationship between primary key to composite key -- phpMyAdmin

I am trying to create a relation between a field 'fldEmpID' in my Employees table to a foreign composite key which consists of fldEmpID and fldEventID but it is not allowing the relation to be created. I don't understand why this relation won't work, I was able to create a similar relation between fldEventID from an Events to the composite key. Both fldEmpID fields in each table are int(11). What can I do to create this relation?
The following are the two tables... (I would like to keep the composite key on the table to the right as it helps to prevent duplicates and works well)
It seems to work as expected for me. I created the tables and used the Designer tab to create the relation (by selecting the "Create relation" icon, then clicking fldEmpId in table a, and finally selecting fldEmpID in table b).
For reference, I pasted below the structure of my table (which includes the keys and restraints)
CREATE TABLE IF NOT EXISTS `a` (
`fldEmpId` int(11) NOT NULL,
`fldEmpName` varchar(50) NOT NULL,
`fldEmail` varchar(50) NOT NULL,
`fldPassHash` varchar(50) NOT NULL,
`fldPassSalt` varchar(50) NOT NULL,
`fldAdmin` enum('1','2') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `b` (
`fldEmpID` int(11) NOT NULL,
`fldEventID` bigint(20) unsigned NOT NULL,
`fldDTAdded` datetime NOT NULL,
`fldDTRemoved` datetime NOT NULL,
`fldPosition` enum('0','1','2','3','4','5') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `a`
ADD PRIMARY KEY (`fldEmpId`);
ALTER TABLE `b`
ADD PRIMARY KEY (`fldEmpID`), ADD UNIQUE KEY `fldEventID` (`fldEventID`);
ALTER TABLE `a`
MODIFY `fldEmpId` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `b`
ADD CONSTRAINT `fk` FOREIGN KEY (`fldEmpID`) REFERENCES `a` (`fldEmpId`);

I get "a foreign key constraint fails" error when attempting to join two classes/tables

I have these classes, abbreviated for practical reasons:
class CV {
Date dateCreated
static hasMany=[proposals: Proposal]
}
class Proposal {
String name
Date date_started
static hasMany = [CVs: CV]
static belongsTo = CV
}
Grails creates tables for both these classes, and a third class named "cv_proposals" joining them. So far, so good. I have data in both the CV and the Proposal tables, they both have autoincremented "id" values. All good.
in Oracle MySQL Workbench, I try to manually add values to the joining table to get some dummy data to work with. I get an error message with this trace:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
(cvreg_utv.cv_proposals, CONSTRAINT FK17D946F55677A672 FOREIGN KEY (cv_id) REFERENCES cv (id))
I made sure both the tables had several lines of data in them, and that I could edit both of them separately.
After trying dropping and recreating the table, altering the classes back and forth, I'm kind of convinced that this operation somehow has to be done through a running Grails application. So I write this script in a controller and run it:
def g = CV.get(1)
Proposal proposal = g.addToProposals(new Proposal(
name: "SavingTest",
date_started: new Date())).save()
I still get the same error, though. Is this not the right way to define a proposal that is connected to a certain CV? Am I wrong in using a many-to-many connection here somehow?
Edit: adding the schema-create script for the joining table
delimiter $$
CREATE TABLE `cv_proposals` (
`proposal_id` bigint(20) NOT NULL,
`cv_id` bigint(20) NOT NULL,
PRIMARY KEY (`cv_id`,`proposal_id`),
KEY `FK17D946F55677A672` (`cv_id`),
KEY `FK17D946F5F7217832` (`proposal_id`),
CONSTRAINT `FK17D946F5F7217832` FOREIGN KEY (`proposal_id`) REFERENCES `proposal` (`id`),
CONSTRAINT `FK17D946F55677A672` FOREIGN KEY (`cv_id`) REFERENCES `cv` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1$$
And the CV table:
CREATE TABLE `cv` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`version` bigint(20) NOT NULL,
`user_id` bigint(20) NOT NULL,
`version_name` varchar(255) DEFAULT NULL,
`date_created` datetime NOT NULL,
`last_updated` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `FKC734A9AB992` (`user_id`)
) ENGINE=MyISAM AUTO_INCREMENT=101 DEFAULT CHARSET=latin1$$
And the Proposal table:
CREATE TABLE `proposal` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`version` bigint(20) NOT NULL,
`date_ended` datetime NOT NULL,
`date_started` datetime NOT NULL,
`description` varchar(500) DEFAULT NULL,
`name` varchar(500) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1$$
This is the insert script I tried to run:
INSERT INTO `cvreg_utv`.`cv_proposals` (`proposal_id`, `cv_id`)
VALUES ('1', '1');
You crated the tables manually? It's interesting that cv table is using MyISAM engine and the others uses InnoDB.
I think you want to use InnoDB to all your tables, since this engine is transactional. In my test, I also was unable to create the cv_proposals table until I changed the cv creation:
CREATE TABLE cv (
id bigint(20) NOT NULL AUTO_INCREMENT,
version bigint(20) NOT NULL,
user_id bigint(20) NOT NULL,
version_name varchar(255) DEFAULT NULL,
date_created datetime NOT NULL,
last_updated datetime NOT NULL,
PRIMARY KEY (id),
KEY FKC734A9AB992 (user_id)
) ENGINE=InnoDB AUTO_INCREMENT=101
After that, the insert's worked smoothly.

I am not able to create foreign key in mysql Error 150. Please help

i am trying to create a foreign key in my table. But when i executes my query it shows me error 150.
Error Code : 1025
Error on create foreign key of '.\vts\#sql-6ec_1' to '.\vts\tblguardian' (errno: 150)
(0 ms taken)
My Queries are
Query to create a foreign Key
alter table `vts`.`tblguardian` add constraint `FK_tblguardian` FOREIGN KEY (`GuardianPickPointId`) REFERENCES `tblpickpoint` (`PickPointId`)
Primary Key table
CREATE TABLE `tblpickpoint` (
`PickPointId` int(4) NOT NULL auto_increment,
`PickPointName` varchar(500) default NULL,
`PickPointLabel` varchar(500) default NULL,
`PickPointLatLong` varchar(100) NOT NULL,
PRIMARY KEY (`PickPointId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC
Foreign Key Table
CREATE TABLE `tblguardian` (
`GuardianId` int(4) NOT NULL auto_increment,
`GuardianName` varchar(500) default NULL,
`GuardianAddress` varchar(500) default NULL,
`GuardianMobilePrimary` varchar(15) NOT NULL,
`GuardianMobileSecondary` varchar(15) default NULL,
`GuardianPickPointId` int(4) default NULL,
PRIMARY KEY (`GuardianId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Your problem is the type of the columns in your constraint are different. They must be the same.
`PickPointId` int(4) NOT NULL auto_increment,
`GuardianPickPointId` varchar(100) default NULL,
For more information see the documentation:
Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.
Have a look at this step by step issue list
MySQL Error Number 1005 Can’t create table ‘.\mydb#sql-328_45.frm’ (errno: 150)

Two n x m relationships with the same table in mysql

I want to create a database in which there's an n x m relationship between the table drug and the table article and an n x m relationship between the table target and the table article.
I get the error: Cannot delete or update a parent row: a foreign key constraint fails
What do I have to change in my code?
DROP TABLE IF EXISTS `textmine`.`article`;
CREATE TABLE `textmine`.`article` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Pubmed ID',
`abstract` blob NOT NULL,
`authors` blob NOT NULL,
`journal` varchar(256) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `textmine`.`drugs`;
CREATE TABLE `textmine`.`drugs` (
`id` int(10) unsigned NOT NULL COMMENT 'This ID is taken from the biosemantics dictionary',
`primaryName` varchar(256) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `textmine`.`targets`;
CREATE TABLE `textmine`.`targets` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`primaryName` varchar(256) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `textmine`.`containstarget`;
CREATE TABLE `textmine`.`containstarget` (
`targetid` int(10) unsigned NOT NULL,
`articleid` int(10) unsigned NOT NULL,
KEY `target` (`targetid`),
KEY `article` (`articleid`),
CONSTRAINT `article` FOREIGN KEY (`articleid`) REFERENCES `article` (`id`),
CONSTRAINT `target` FOREIGN KEY (`targetid`) REFERENCES `targets` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `textmine`.`contiansdrug`;
CREATE TABLE `textmine`.`contiansdrug` (
`drugid` int(10) unsigned NOT NULL,
`articleid` int(10) unsigned NOT NULL,
KEY `drug` (`drugid`),
KEY `article` (`articleid`),
CONSTRAINT `article` FOREIGN KEY (`articleid`) REFERENCES `article` (`id`),
CONSTRAINT `drug` FOREIGN KEY (`drugid`) REFERENCES `drugs` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
You are trying to create tables out of order.
For example you are trying to create contiansdrug table which refers to table drugs before drugs table.
Remember that any SQL, even DDL, tries to leave database in consistent state.
I would recommend putting the commands in proper order. Alternatively you have options to turn off the checks temporarily and run the creation scrip inside transaction, see the instructions here
Relevant section is
SET AUTOCOMMIT = 0;
SET FOREIGN_KEY_CHECKS=0;
.. your script..
SET FOREIGN_KEY_CHECKS = 1;
COMMIT;
SET AUTOCOMMIT = 1;
EDIT:
OK, try not to have same names for constraints. Reading the fine manual enlightens:
If the CONSTRAINT symbol clause is
given, the symbol value must be unique
in the database. If the clause is not
given, InnoDB creates the name
automatically.
EDIT2:
To spell it out, you have duplicate constrain symbol article, rename it and all will be fine.
Standard practice is if you name your constrains to use names that describe what is related, for example containsdrug_acticelid_article_id (firsttablename_column_secondtablename_column) would be unique and descriptive.
I solved the problem by not declaring the Foreign Key inside of MySql but simply declaring them as ints.