how to fix Error in EER diagram to create tables? - mysql

when I wanted to generate tables, I got this error I don't know how to fix it. Is anyone face to this problem and how you solve it?
thanks
CREATE TABLE IF NOT EXISTS `tb_inv_detail` (
`inv_id_fk` INT UNSIGNED NOT NULL,
`part_id_fk` INT UNSIGNED NOT NULL,
`qty` DECIMAL(12,2) NOT NULL,
`tb_detailed` VARCHAR(50) NULL,
`tb_inv_detailcol` VARCHAR(45) NULL,
PRIMARY KEY (`inv_id_fk`),
INDEX `fk_tb_inv_detail_tb_parts1_idx` (`part_id_fk` ASC) VISIBLE,
CONSTRAINT `fk_tb_inv_detail_tb_parts1`
FOREIGN KEY (`part_id_fk`)
REFERENCES `tb_parts` (`part_id_pk`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_tb_inv_detail_tb_invoice1`
FOREIGN KEY (`inv_id_fk`)
REFERENCES `tb_invoice` (`inv_id_pk`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
SQL script execution finished: statements: 25 succeeded, 1 failed
Also this screenshot of my EER diagram:

Well the obvious code which is missing from what you posted above is the DDL for the two tables referred to by the foreign keys defined in tb_inv_detail. These tables are:
tb_parts
tb_invoice
These tables must be defined first, with correctly named primary key columns to match the foreign keys in your table above.
CREATE TABLE tb_parts (
part_id_pk INT UNSIGNED NOT NULL,
PRIMARY KEY (part_id_pk), -- referred to by part_id_fk
...
)
CREATE TABLE tb_invoice (
inv_id_pk INT UNSIGNED NOT NULL,
PRIMARY KEY (inv_id_pk), -- referred to by inv_id_fk
...
)

Related

MySQL Foreign key constraint are incompatible

MySQL Version 8.0.17
The full error reads:
Referencing column 'groupLineId' and referenced column 'groupLineId' in foreign key constraint 'salesItemLine-groupLine' are incompatible
I am trying to link two tables via the groupLineId which are both NOT NULL VARCHAR(12). I am not sure why I am getting the error. I have several other foreign key relationships like this in my DB.
I am using the following code to generate the two tables. (Note: code for invoice table not shown)
CREATE TABLE IF NOT EXISTS `reports`.`groupLine` (
`groupLineId` VARCHAR(12) NOT NULL,
`lineNum` INT NOT NULL,
`invoiceId` VARCHAR(12) NOT NULL,
PRIMARY KEY (`groupLineId`, `lineNum`, `invoiceId`),
INDEX `groupLine-invoice_idx` (`invoiceId` ASC) VISIBLE,
CONSTRAINT `groupLine-invoice`
FOREIGN KEY (`invoiceId`)
REFERENCES `reports`.`invoice` (`invoiceId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `reports`.`salesItemLine` (
`groupLineId` VARCHAR(12) NOT NULL,
`lineNum` INT NOT NULL,
`description` VARCHAR(256) NULL,
`amount` DECIMAL NULL,
`detailType` VARCHAR(45) NULL,
PRIMARY KEY (`groupLineId`, `lineNum`),
INDEX `salesItemLine-groupLine_idx` (`groupLineId` ASC) VISIBLE,
CONSTRAINT `salesItemLine-groupLine`
FOREIGN KEY (`groupLineId`)
REFERENCES `reports`.`groupLine` (`groupLineId`)
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
If anyone comes across this my problem was how I was making changes and using the "Forward Engineer" feature of MySQL Workbench. I had originally created the database with groupLineId ID as type INT. I then changed the model to make the groupLineId in both tables to VARCHAR(12). Then when I would run "Forward Engineer" it would first write the new groupLine table and change the type of groupLineId to VARCHAR(12) this would then break the existing FROGIEN key with salesItemLine table which has not been updated and still has the type of groupeLineId as INT.
The solution was to DROP both tables before rerunning the forward engineering. (Or at least manually dropping the existing constraints)

Error code 1215: cannot add foreign key constraint MySQL

I'm having a problem creating a database in MySQL.
The error code:'Error code 1215: cannot add foreign key constraint' pops up when i try to implement my changes. I've paid attention to all the necessary things but i can't find the solution.
This error only happened after i added some tables after having made an initial database(which did work), so hopefully i'm not dealing with this problem throughout the whole project.
Here's a snippet of the code in which the error occurs, the foreign key that's not working correctly is 'tournament_id' referencing to 'id' in tournament:
CREATE DATABASE allin;
USE allin;
CREATE TABLE employee (
phone_number char(12) NOT NULL,
birth_date date NOT NULL,
tournament_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(phone_number),
FOREIGN KEY(tournament_id) REFERENCES tournament(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Second table:
CREATE TABLE tournament (
id int NOT NULL AUTO_INCREMENT,
date date NOT NULL,
time time NOT NULL,
cost decimal(5,2) NOT NULL,
min_players int NOT NULL,
min_age int NOT NULL,
max_age int NOT NULL,
location_id int NULL,
winner_id int NULL,
type varchar(40) NULL,
PRIMARY KEY(id),
FOREIGN KEY(winner_id) REFERENCES player(id) ON DELETE SET NULL ON UPDATE CASCADE,
FOREIGN KEY(location_id) REFERENCES event_location(id) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The issue is here:
FOREIGN KEY(tournament_id) REFERENCES tournament(id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
the above query is of CREATE TABLE employee. In this query, you are creating a FOREIGN KEY that refers to tournament(id), but as of now there is no tournament table exist in the specified database as the tournament table create query is reside below in the sequence.
I layman terms we can say, you are trying to refer a table column that
do not exist.
So to resolve this, run all you parent table creation query first, and than child table.
tournament_id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(phone_number)
Hey, I don't think you could set another primary key while an "auto increment" already exist

Cannot create foreign key to different database in mysql

I have two tables on different databases in mysql. I'm trying to create a composite foreign key from one table to the other and for some reason it doesn't work. It only works if I use a single primary key field instead of a composite key.
The problematic constraint in the example below is fk_dummy_table11. I get Error Code: 1215. Cannot add foreign key constraint when executing the statement.
Create table statement for "dummy" in DB NREAP:
CREATE TABLE IF NOT EXISTS `NREAP`.`dummy` (
`id` INT NOT NULL,
`table1_TDO_COD_TIP_DOC` VARCHAR(14) NOT NULL,
`table1_RFI_NUM_DOC` INT NOT NULL,
`table1_RFI_VER_DOC` INT NOT NULL,
`table1_RFI_NOM_FIC` VARCHAR(128) NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_dummy_table11_idx` (`table1_TDO_COD_TIP_DOC` ASC, `table1_RFI_NUM_DOC` ASC, `table1_RFI_VER_DOC` ASC, `table1_RFI_NOM_FIC` ASC),
CONSTRAINT `fk_dummy_table11`
FOREIGN KEY (`table1_TDO_COD_TIP_DOC` , `table1_RFI_NUM_DOC` , `table1_RFI_VER_DOC` , `table1_RFI_NOM_FIC`)
REFERENCES `TRANS`.`table1` (`TDO_COD_TIP_DOC` , `RFI_NUM_DOC` , `RFI_VER_DOC` , `RFI_NOM_FIC`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Create table statement for "table1" in DB TRANS:
CREATE TABLE IF NOT EXISTS `TRANS`.`table1` (
`TDO_COD_TIP_DOC` VARCHAR(14) NOT NULL,
`RFI_NUM_DOC` INT NOT NULL,
`RFI_VER_DOC` INT NOT NULL,
`RFI_NOM_FIC` VARCHAR(128) NOT NULL,
`RFI_LOC_FIC` VARCHAR(1000) NULL,
`RFI_DES_FIC` VARCHAR(255) NULL,
`RFI_TIPO` VARCHAR(100) NOT NULL,
`DAT_ALT` DATE NOT NULL,
`COD_UTI_ALT` VARCHAR(14) NOT NULL,
`DFI_VER_DOC` INT NULL,
`DFI_NUM_SEQ` INT NULL,
`CAM_ANO_INI_CAM` VARCHAR(4) NULL,
PRIMARY KEY (`TDO_COD_TIP_DOC`, `RFI_NUM_DOC`, `RFI_VER_DOC`, `RFI_NOM_FIC`))
ENGINE = InnoDB;
Please help, this is so frustrating...
Edit1 - I'm running mysql version 5.7.12
Edit2 - I've ran the SHOW ENGINE INNODB STATUS command, it gives me the following output:
I'm running mysql version 5.7.12, it's the latest one I think.
I've ran innodb status:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2016-07-13 10:28:34 0x124c Error in foreign key constraint of table nreap/dummy:
FOREIGN KEY (`table1_TDO_COD_TIP_DOC` , `table1_RFI_NUM_DOC` , `table1_RFI_VER_DOC` , `table1_RFI_NOM_FIC`)
REFERENCES `TRANS`.`table1` (`TDO_COD_TIP_DOC` , `RFI_NUM_DOC` , `RFI_VER_DOC` , `RFI_NOM_FIC`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB:
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.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
Please refer to http://dev.mysql.com/doc/refman/5.7/en/innodb-foreign-key-constraints.html for correct foreign key definition.
I've eventually figured out the problem.
I've narrowed it down to a problem in using VARCHAR keys, the restraint worked fine with other datatypes. After a few experiments I've added a specific charset for each schema and it worked. Adding the specific charset to each table also works.
Thanks for the help!

Mysql error # 1215

I have been using mySQL to create a database but when I try to forward engineer my EER Diagram the database keeps sending me back the same error I have tried multiple fixes does anyone see what the problem is? The error code is 1215
Executing SQL script in server
ERROR: Error 1215: Cannot add foreign key constraint
SQL Code:
-- -----------------------------------------------------
-- Table `mydb`.`Employee`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Employee` (
`EID` INT NOT NULL,
`Fname` VARCHAR(45) NOT NULL,
`Lname` VARCHAR(45) NOT NULL,
`AddressID` INT NOT NULL,
`PayLevel` FLOAT NOT NULL,
`Jobtitle` VARCHAR(45) NOT NULL,
`Date of Employment` DATE NOT NULL,
PRIMARY KEY (`EID`),
CONSTRAINT `fk_Employee_Store1`
FOREIGN KEY (`EID`)
REFERENCES `mydb`.`Store` (`EID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
SQL script execution finished: statements: 8 succeeded, 1 failed
Fetching back view definitions in final form.
Nothing to fetch
This is the parent code, multiple times I have tried switching the relationships however employee9the top code) should be a child of Store.
-- -----------------------------------------------------
-- Table `mydb`.`Store`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`Store` (
`SID` INT NOT NULL,
`StoreName` VARCHAR(45) NULL,
`AddressID` INT NULL,
`EID` INT NOT NULL,
`CID` INT NULL,
`MID` INT NULL,
PRIMARY KEY (`SID`, `EID`),
INDEX `fk_Store_Employee1_idx` (`EID` ASC),
CONSTRAINT `fk_Store_Employee1`
FOREIGN KEY (`EID`)
REFERENCES `mydb`.`Employee` (`EID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Does anyone see the problem, Btw I have checked the type's multiple times they are equivalent.
you are trying to create a foreign key in store from employee and another one in employee from store.
if this is a parent/child relation then only the primary key from the parent that is used in the child.
if you have n<->n relation then you need a new table that holds both foreign keys.
if I understand, here you need to have a new table (work) with (SID, EID) where both point to their respective tables (store and employee). Also creation order is important (parents first then child tables).
You have a foreign key constraint operating in both directions. When you're creating the tables the first to be created will fail because the second doesn't exist. I'm not even sure that MySQL will accept a circular reference like this. You should probably remove the foreign key constraint applied to mydb.store
However, if this is essential you can ask MySQL to ignore the foreign key checks while you create the table. Just execute
SET foreign_key_checks = 0;
before you create the tables and
SET foreign_key_checks = 1;
after you finish

Foreign key between MySQL InnoDB tables not working...why?

I have the following tables:
specie (MyIsam)
image (InnoDB)
specie_map (InnoDB)
The specie_map table should map an image to a specie, and therefore has the following columns:
specie_id
image_id
Both are int 11, just like the id columns of the specie and image tables. I know I can't create a foreign key between specie_id and specie=>id, since the specie table is a MyIsam table. However, I would expect it to be possible to create a foreign key between image_id and image=>id.
I can create that foreign key and it will save it, however, the CASCADE action I have associated with it does not work. When I delete an image, it does not delete the specie_map entry that is associated with it. I would expect this to work, as this foreign key is between InnoDB tables. Both columns are indexed and of the same data type.
Is this a limitation of MySQL, or am I doing something else wrong?
Update: as requested hereby the table definitions. I have snipped unimportant columns:
-- ----------------------------
-- Table structure for `image`
-- ----------------------------
DROP TABLE IF EXISTS `image`;
CREATE TABLE `image` (
`id` int(11) NOT NULL auto_increment,
`guid` char(36) default NULL,
`title` varchar(255) NOT NULL,
`description` text,
`user_id` int(11) NOT NULL,
`item_id` int(11) default NULL,
`date_uploaded` timestamp NOT NULL default '0000-00-00 00:00:00',
`date_created` timestamp NOT NULL default '0000-00-00 00:00:00',
`date_modified` timestamp NOT NULL default '0000-00-00 00:00:00',
`status` enum('softdeleted','tobedeleted','active') default 'active',
PRIMARY KEY (`id`),
KEY `image_user` (`user_id`),
KEY `image_item` (`item_id`),
KEY `image_mod_by` (`moderated_by`),
CONSTRAINT `image_mod_by` FOREIGN KEY (`moderated_by`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `image_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='stores image data (not file data)';
-- ----------------------------
-- Table structure for `specie`
-- ----------------------------
DROP TABLE IF EXISTS `specie`;
CREATE TABLE `specie` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(256) NOT NULL,
`commonname` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=22 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
-- ----------------------------
-- Table structure for `specie_map`
-- ----------------------------
DROP TABLE IF EXISTS `specie_map`;
CREATE TABLE `specie_map` (
`id` int(11) NOT NULL auto_increment,
`image_id` int(11) NOT NULL,
`specie_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`karma` int(11) NOT NULL,
`date_created` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `image_id` (`image_id`),
KEY `specie_id` (`specie_id`),
CONSTRAINT `specie_map_ibfk_1` FOREIGN KEY (`image_id`) REFERENCES `image` (`id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Foreign keys works only with InnoDb in mysql. MyISAM doesn't support them (the statements are ignored).
And is there any reason why you mix multiple DB engines?
I think you should post the exact DDL statements you used when you attempted to create these tables and the foreign key. Foreign keys between innodb tables work fine, but there are still a few things to look out for:
0) Both tables must be InnoDB. This was already highlighted by the other posters and this is probably the immediate cause of your problem.
1) the data type of the referencing columns (those that make up the foreign key) and their respective referenced columns should be the same. For example, you can't create a foreign key constrain on an INT UNSIGNED column to a plain INT column.
2) if the foreign key is created as part of the table DDL, be sure to put the foreign key definition in the constraints section, that is, below all column definitions. For example:
CREATE TABLE parent (
id int unsigned PRIMARY KEY
);
CREATE TABLE child (
parent_id int unsigned
, foreign key (parent_id)
references parent (id)
);
will work but this:
CREATE TABLE child (
parent_id int unsigned
foreign key references parent (id)
);
won't. It will fail silently because MySQL's parser ignores these types of constraint definitions even before InnoDB gets to create the table (silly, but that's how it is)
3) There must be an index over all the referenced columns. Usually the referenced columns will together make up a primary key or a unique constraint anyway, but it is your job to define this before defining the foreign key.
Final word of advice: if you think your DDL is ok but you still get an error when you execute it, for example like this:
ERROR 1005 (HY000): Can't create table 'test.child' (errno: 150)
Warning (Code 150): Create table 'test/child' with foreign key constraint failed. There is no index in the referenced table where the referenced columns appear as the first columns.
Error (Code 1005): Can't create table 'test.child' (errno: 150)
Then these errors may still not reveal the true nature of the error (silly again, but that's how it is). To shed more light on it, run this command immediately after your attempt to create the foreign key:
SHOW ENGINE INNODB STATUS;
This will give you a bunch of status info, and one section there looks like this:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
120122 11:38:28 Error in foreign key constraint of table test/child:
foreign key (parent_id) references parent (id) ):
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.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
As you can see, this gives a bit more information and reveals the true problem, namely "column types in the table and the referenced table do not match for constraint"
So please, post your actual DDL, I'm sure there is a problem in there somewhere.