Question

I have tried create this table, but nothing I have tried works from FKs.

CREATE TABLE `tb_AutSituacao` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `Nome` varchar(50) CHARACTER SET latin1 NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

CREATE TABLE `tb_AutHistorico` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `Situacao` int(11) NOT NULL,
 `Data` date NOT NULL,
 `Agente` int(11) NOT NULL,
 `Proposta` int(11) NOT NULL,
 PRIMARY KEY (`id`),
 KEY `AutHistorico_Situacao` (`Situacao`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

ALTER TABLE `tb_AutHistorico` ADD FOREIGN KEY ( `Situacao` ) REFERENCES `sicor`.`tb_AutSituacao` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT;

I always get "#1005 - Can't create table 'tablename' (errno: 150)". Thanks for help.

Was it helpful?

Solution

$ perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed

Fix your FOREIGN KEY definition.

OTHER TIPS

There is an issue with your foreign key constraint definition (See http://dev.mysql.com/doc/refman/5.7/en/innodb-foreign-key-constraints.html - last paragraph for debugging)

When this error occurs, either the definition itself is incorrect (syntax error) OR there is an issue with what is being referenced. Your syntax is correct, what is references is correct, so it's most likely the schema reference.

I can run the statements fine on my end, but I had to prefix the create table names with the schema name. Otherwise, MySQL will assume that you are trying to create the table for the database you are currently using. Please see following modified statements:

CREATE TABLE `sicor`.`tb_AutSituacao` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `Nome` varchar(50) CHARACTER SET latin1 NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

CREATE TABLE `sicor`.`tb_AutHistorico` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `Situacao` int(11) NOT NULL,
 `Data` date NOT NULL,
 `Agente` int(11) NOT NULL,
 `Proposta` int(11) NOT NULL,
 PRIMARY KEY (`id`),
 KEY `AutHistorico_Situacao` (`Situacao`),
 CONSTRAINT `FK_Situacao` FOREIGN KEY (`Situacao`) REFERENCES `sicor`.`tb_AutSituacao` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

Also please note that you do not have to define a constraint after creating the table, instead you can include it in the create definition as shown above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top