Why MySQL does not accept my foreign keys? - mysql

I have 26 tables that are very dependent from each other. I crated each table and then executed in the database through MySQL Workbench. Then I build the model where I linked those tables creating the foreign keys. I exported that back in to metadata and I had now the complete code of the tables with the proper foreign data created by the application, so I made not mistakes.
But when I put the file in my server to run by phpMyAdmin, I get a 150 error that does not specify where it is. I Googled it but each case is different and mine is that the FK are not the auto incremented field, but a string field called UT that I created which has the Time Unit when I created a row.
CREATE TABLE IF NOT EXISTS `eduardo8_plataforma`.`aplicativo` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT ,
`ut` VARCHAR(20) NOT NULL ,
`nome` VARCHAR(99) NOT NULL ,
`ver` VARCHAR(20) NULL DEFAULT NULL ,
`descr` VARCHAR(254) NULL DEFAULT NULL ,
`tag` VARCHAR(254) NULL DEFAULT NULL ,
`url` VARCHAR(254) NULL DEFAULT NULL ,
`cad` VARCHAR(20) NULL DEFAULT NULL ,
`obj` TEXT NULL DEFAULT NULL ,
`tab` VARCHAR(254) NULL DEFAULT NULL ,
`dbn` VARCHAR(254) NULL DEFAULT NULL ,
`dbu` VARCHAR(254) NULL DEFAULT NULL ,
`dbs` VARCHAR(254) NULL DEFAULT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `nome` (`nome` ASC) ,
UNIQUE INDEX `ut_UNIQUE` (`ut` ASC) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_swedish_ci;
CREATE TABLE IF NOT EXISTS `eduardo8_plataforma`.`modulo` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT ,
`ut` VARCHAR(20) NOT NULL ,
`app` VARCHAR(20) NULL DEFAULT NULL ,
`lic` VARCHAR(20) NULL DEFAULT NULL ,
`tipo` VARCHAR(20) NULL DEFAULT NULL ,
`nome` VARCHAR(99) NOT NULL ,
`classe` VARCHAR(99) NOT NULL ,
`obj` TEXT NULL DEFAULT NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `ut_UNIQUE` (`ut` ASC) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_swedish_ci;
CREATE TABLE IF NOT EXISTS `eduardo8_plataforma`.`modulo_app` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT ,
`ut` VARCHAR(20) NOT NULL ,
`app` VARCHAR(20) NOT NULL ,
`modulo` VARCHAR(20) NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_modulo_app_modulo1` (`modulo` ASC) ,
INDEX `fk_modulo_app_aplicativo1` (`app` ASC) ,
UNIQUE INDEX `ut_UNIQUE` (`ut` ASC) ,
CONSTRAINT `fk_modulo_app_modulo1`
FOREIGN KEY (`modulo` )
REFERENCES `eduardo8_plataforma`.`modulo` (`ut` )
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_modulo_app_aplicativo1`
FOREIGN KEY (`app` )
REFERENCES `eduardo8_plataforma`.`aplicativo` (`ut` )
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_swedish_ci;
The table that worked (after answers):
CREATE TABLE IF NOT EXISTS `eduardo8_plataforma`.`modulo_app` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT ,
`ut` VARCHAR(20) CHARACTER SET 'utf8' COLLATE 'utf8_swedish_ci' UNIQUE NOT NULL ,
`app` VARCHAR(20) CHARACTER SET 'utf8' COLLATE 'utf8_swedish_ci' NOT NULL ,
`modulo` VARCHAR(20) CHARACTER SET 'utf8' COLLATE 'utf8_swedish_ci' NOT NULL ,
PRIMARY KEY (`id`) ,
INDEX `fk_modulo_app_modulo1` (`modulo` ASC) ,
INDEX `fk_modulo_app_aplicativo1` (`app` ASC) ,
UNIQUE INDEX `ut_UNIQUE` (`ut` ASC) ,
CONSTRAINT `fk_modulo_app_modulo1`
FOREIGN KEY (`modulo` )
REFERENCES `eduardo8_plataforma`.`modulo` (`ut` )
ON DELETE CASCADE
ON UPDATE NO ACTION,
CONSTRAINT `fk_modulo_app_aplicativo1`
FOREIGN KEY (`app` )
REFERENCES `eduardo8_plataforma`.`aplicativo` (`ut` )
ON DELETE CASCADE
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_swedish_ci;

You need to move the CREATE INDEX clauses before the foreign keys, as foreign key cannot reference non-indexed field.

The short story is that a foreign key should reference a candidate key column. That is, it should reference a column that is declared either
primary key, or
not null unique.
A standard SQL dbms will raise an error if you reference a column that isn't unique. MySQL should, too, but it won't.
Mysql Docs say
. . . the system does not enforce a requirement that the referenced columns
be UNIQUE or be declared NOT NULL. The handling of foreign key
references to nonunique keys or keys that contain NULL values is not
well defined for operations such as UPDATE or DELETE CASCADE. You are
advised to use foreign keys that reference only UNIQUE (including
PRIMARY) and NOT NULL keys.
If you need non-unique data from another table, join it in a query, or join it in a view.

Related

error 1215 MYSQL Cannot add foreign key constraint,

I have this code:
CREATE TABLE IF NOT EXISTS `biblioteca`.`ejemplar` (
`idejemplar` INT(11) NOT NULL AUTO_INCREMENT ,
`estado` VARCHAR(45) NOT NULL ,
`comentario` VARCHAR(45) NULL ,
`isbn` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`idejemplar`) ,
INDEX `fk_ejemplar_libro1_idx` (`isbn` ASC) ,
CONSTRAINT `fk_ejemplar_libro1`
FOREIGN KEY (`isbn` )
REFERENCES `biblioteca`.`libro` (`isbn` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
and the table that's makes reference is:
CREATE TABLE IF NOT EXISTS `biblioteca`.`libro` (
`isbn` VARCHAR(25) NOT NULL ,
`idcategoria` INT(11) NOT NULL ,
`ideditorial` INT(11) NOT NULL ,
`titulo` VARCHAR(45) NOT NULL ,
`autor` VARCHAR(45) NOT NULL ,
`reseña` VARCHAR(45) NULL ,
PRIMARY KEY (`isbn`) ,
INDEX `fk_libro2_idx` (`idcategoria` ASC) ,
INDEX `fk_libro3_idx` (`ideditorial` ASC) ,
CONSTRAINT `fk_libro2`
FOREIGN KEY (`idcategoria` )
REFERENCES `biblioteca`.`categoria` (`idcategoria` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_libro3`
FOREIGN KEY (`ideditorial` )
REFERENCES `biblioteca`.`editorial` (`ideditorial` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
and i think thats foreign keys are good.
If these are fresh tables with no values, It seems like an error with the columns
one has a varchar(25) the other a var_char(45) make them the same
edit:
CREATE TABLE IF NOT EXISTS `biblioteca`.`libro` (
`isbn` VARCHAR(45) NOT NULL ,
`idcategoria` INT(11) NOT NULL ,
`ideditorial` INT(11) NOT NULL ,
`titulo` VARCHAR(45) NOT NULL ,
`autor` VARCHAR(45) NOT NULL ,
`reseña` VARCHAR(45) NULL ,
PRIMARY KEY (`isbn`) ,
INDEX `fk_libro2_idx` (`idcategoria` ASC) ,
INDEX `fk_libro3_idx` (`ideditorial` ASC) )
ENGINE = INNODB
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `biblioteca`.`ejemplar` (
`idejemplar` INT(11) NOT NULL AUTO_INCREMENT ,
`estado` VARCHAR(45) NOT NULL ,
`comentario` VARCHAR(45) NULL ,
`isbn` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`idejemplar`) ,
INDEX `fk_ejemplar_libro1_idx` (`isbn` ASC) ,
CONSTRAINT `fk_ejemplar_libro1`
FOREIGN KEY (`isbn` )
REFERENCES `biblioteca`.`libro` (`isbn` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = INNODB
DEFAULT CHARACTER SET = utf8;
works no problem for me. Ive taken away the other 2 keys which i dont have schemas for though

Can't create table in MySQL [error 150] when use foreign key

I have designed schema with MySQL workbench.
But it couldn't complete Database Synchronize.It can create tables with out foreign keys.
I copied SQL from MySQL WorkBench to execute in phpmysqadmin.
CREATE TABLE IF NOT EXISTS `Books`.`Users` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`mail` VARCHAR(45) NOT NULL ,
`password` VARCHAR(45) NOT NULL ,
`smspassword` VARCHAR(8) NULL ,
`mobile` VARCHAR(16) NULL ,
`type` ENUM('admin','secretery','groupadmin','user') NOT NULL DEFAULT 'user' ,
`securelogin` ENUM('true','false') NULL DEFAULT 'true' ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `id_UNIQUE` (`id` ASC) ,
UNIQUE INDEX `mail_UNIQUE` (`mail` ASC) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci
COMMENT = 'Table to store users data'
Users table created successfully. But following table (Profile) can't be created.
CREATE TABLE IF NOT EXISTS `Books`.`Profiles` (
`id` INT NOT NULL AUTO_INCREMENT ,
`firstname` VARCHAR(45) NOT NULL ,
`lastname` VARCHAR(45) NOT NULL ,
`title` VARCHAR(45) NOT NULL ,
`nationalcode` VARCHAR(45) NOT NULL ,
`User_id` INT NOT NULL ,
PRIMARY KEY (`id`, `User_id`) ,
INDEX `fk_Profiles_Users` (`User_id` ASC) ,
CONSTRAINT `fk_Profiles_Users`
FOREIGN KEY (`User_id` )
REFERENCES `Books`.`Users` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci
But it will be return:
#1005 - Can't create table 'Books.Profiles' (errno: 150)
Where is the problem, and how should I solve this?
You need to match the primary id column type with the foreign key column type - your primary id in Users is UNSIGNED INT, but your foreign key in Profiles is INT. Try this:
CREATE TABLE IF NOT EXISTS `Books`.`Profiles` (
`id` INT NOT NULL AUTO_INCREMENT ,
`firstname` VARCHAR(45) NOT NULL ,
`lastname` VARCHAR(45) NOT NULL ,
`title` VARCHAR(45) NOT NULL ,
`nationalcode` VARCHAR(45) NOT NULL ,
`User_id` INT UNSIGNED NOT NULL , -- <<= Check the type here!
PRIMARY KEY (`id`, `User_id`) ,
INDEX `fk_Profiles_Users` (`User_id` ASC) ,
CONSTRAINT `fk_Profiles_Users`
FOREIGN KEY (`User_id` )
REFERENCES `Books`.`Users` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_unicode_ci;

Source not available during model and database syc in MySQL work Bench

I am trying to update a table and sync it with the source but the source isnt available as you can see in the screen shot
and the script is
CREATE TABLE IF NOT EXISTS `DAHMS`.`Answers` (
`aid` INT(11) NOT NULL AUTO_INCREMENT ,
`qid` INT(11) NOT NULL ,
`sid` INT(11) NOT NULL ,
`answer` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`aid`) ,
INDEX `fk_Answers_Session1_idx` (`sid` ASC) ,
INDEX `fk_Answers_Questions1_idx` (`qid` ASC) ,
CONSTRAINT `fk_Answers_Session1`
FOREIGN KEY (`sid` )
REFERENCES `DAHMS`.`Session` (`sid` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Answers_Questions1`
FOREIGN KEY (`qid` )
REFERENCES `DAHMS`.`Questions` (`qid` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = latin1
COLLATE = latin1_swedish_ci

Mysql Forward engineer errno 150

I'm modeling my db shema using MySQL Workbench CE EER modeler and now I'm stuck with mysql errno 150.
My sql code:
CREATE TABLE `myschema`.`Clients` (
`phone` VARCHAR(15) NOT NULL ,
`surname` VARCHAR(30) NOT NULL ,
`name` VARCHAR(30) NOT NULL ,
`middleName` VARCHAR(30) NULL ,
`discountCardNumber` BIGINT NULL ,
PRIMARY KEY (`phone`) ,
UNIQUE INDEX `discountCardNumber_UNIQUE` (`discountCardNumber` ASC) ,
CONSTRAINT `fk_Clients_DiscountCards1`
FOREIGN KEY (`discountCardNumber` )
REFERENCES `myschema`.`DiscountCards` (`cardNumber` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB;
CREATE TABLE `myschema`.`OrderStatuses` (
`statusID` INT NOT NULL AUTO_INCREMENT ,
`statusTitle` VARCHAR(45) NOT NULL ,
`statusDescription` VARCHAR(150) NULL ,
PRIMARY KEY (`statusID`) )
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `myschema`.`WorkstationUsers` (
`userID` INT NOT NULL AUTO_INCREMENT ,
`login` VARCHAR(45) NOT NULL ,
`pass` VARCHAR(45) NOT NULL ,
`name` VARCHAR(45) NOT NULL ,
`surname` VARCHAR(45) NOT NULL ,
`middleName` VARCHAR(45) NULL ,
PRIMARY KEY (`userID`) )
ENGINE = InnoDB;
CREATE TABLE `myschema`.`Orders` (
`orderID` BIGINT NOT NULL AUTO_INCREMENT ,
`registerDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`clientPhone` VARCHAR(15) NOT NULL ,
`shipmentAddress` VARCHAR(150) NOT NULL ,
`orderStatus` INT NOT NULL ,
`registrator` INT NOT NULL ,
PRIMARY KEY (`orderID`) ,
INDEX `fk_Orders_Clients` (`clientPhone` ASC) ,
INDEX `fk_Orders_OrderStatuses1` (`orderStatus` ASC) ,
INDEX `fk_Orders_WorkstationUsers1` (`registrator` ASC) ,
CONSTRAINT `fk_Orders_Clients`
FOREIGN KEY (`clientPhone` )
REFERENCES `myschema`.`Clients` (`phone` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Orders_OrderStatuses1`
FOREIGN KEY (`orderStatus` )
REFERENCES `myschema`.`OrderStatuses` (`statusID` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Orders_WorkstationUsers1`
FOREIGN KEY (`registrator` )
REFERENCES `myschema`.`WorkstationUsers` (`userID` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB;
It fails in last statement (CREATE TABLE Orders).
I already checked:
Types of refferencing tables are equals
Indexes on all columns exists
Engine is InnoDB
Thanks for any help! Have a good day!
P.S. sorry for possible duplicate. I really can't find any problem in my code.
Some of fields are defined as NOT NULL, but you defined 'ON DELETE' action as 'SET NULL'.
Make these fields nullabe -
CREATE TABLE `myschema`.`Orders` (
`orderID` BIGINT NOT NULL AUTO_INCREMENT ,
`registerDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`clientPhone` VARCHAR(15) NULL, -- NOT NULL ,
`shipmentAddress` VARCHAR(150) NOT NULL ,
`orderStatus` INT NULL, -- NOT NULL ,
`registrator` INT NULL, -- NOT NULL ,
PRIMARY KEY (`orderID`) ,
INDEX `fk_Orders_Clients` (`clientPhone` ASC) ,
INDEX `fk_Orders_OrderStatuses1` (`orderStatus` ASC) ,
INDEX `fk_Orders_WorkstationUsers1` (`registrator` ASC) ,
CONSTRAINT `fk_Orders_Clients`
FOREIGN KEY (`clientPhone` )
REFERENCES `myschema`.`Clients` (`phone` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Orders_OrderStatuses1`
FOREIGN KEY (`orderStatus` )
REFERENCES `myschema`.`OrderStatuses` (`statusID` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Orders_WorkstationUsers1`
FOREIGN KEY (`registrator` )
REFERENCES `myschema`.`WorkstationUsers` (`userID` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB;
In my case, the problem was solved by adding
DEFAULT CHARACTER SET = utf8
at the end of each create table
regards!

Can't create mysql table with foreign key

I am getting errno 150 when I try to create the following two tables.
CREATE TABLE `mydatabase`.`userstatus`(
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` VARCHAR(50) NOT NULL ,
`description` VARCHAR(255) ,
PRIMARY KEY (`id`)
);
CREATE TABLE `mydatabase`.users(
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`email` VARCHAR(200) NOT NULL ,
`username` VARCHAR(20) NOT NULL DEFAULT 'Unknown' ,
`userstatusid` INT UNSIGNED NOT NULL DEFAULT 2 ,
`datemodified` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`datecreated` DATETIME DEFAULT 0 NOT NULL ,
PRIMARY KEY (`id`),
UNIQUE (username),
UNIQUE (email),
INDEX userstatusid_index (userstatusid),
CONSTRAINT fk_users_userstatus FOREIGN KEY (userstatusid) REFERENCES userstatus(id)
ON DELETE SET NULL
ON UPDATE CASCADE
) ENGINE=INNODB ROW_FORMAT=DEFAULT ;
What's causing the error and how do I fix it?
I put on delete set null but the column has been defined as not null. I was focusing too much attention to the types which usually causes the errno 150.
Maybe you could try set a Unique key on userstatusid.
Sometimes that may help.
You can try SHOW INNODB STATUS which will show the last InnoDB error (e.g. foreign key constraint definition problems).
(Otherwise you have to just guess based on the error number and limited information which the error from the statement provides, which isn't ideal.)