Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql error on create table

Tags:

mysql

I want to create a table with Primary key referenced to Two columns of other table on MySql Something like this

CREATE  TABLE IF NOT EXISTS `tarina`.`Geo_Distrito` (
  `departamento` INT(10) NOT NULL ,
  `provincia` INT(10) NOT NULL ,
  `codigo` INT(10) NOT NULL ,
  `nombre` VARCHAR(80) NULL ,
  `estado` INT(10) NULL ,
  PRIMARY KEY (`departamento`, `provincia`, `codigo`) ,
  CONSTRAINT `FK_ProvinciaDistrito`  FOREIGN KEY (`departamento` , `provincia` )  REFERENCES `Geo_Provincia` (`departamento` , `codigo` )
)ENGINE = InnoDB;

And got this error:

Can't create table 'tarina.Geo_Distrito' (errno: 150)

Can someone tell me what is the problem?

like image 474
jcvegan Avatar asked Feb 07 '12 03:02

jcvegan


1 Answers

Cannot create table. If the error message refers to error 150, table creation failed because a foreign key constraint was not correctly formed. If the error message refers to error –1, table creation probably failed because the table includes a column name that matched the name of an internal InnoDB table.

This is due because of the the definition of your column has to be the same. In your case:

the columns are not the same type, codigo int(10) unsigned NOT NULL and codigo INT(10) NOT NULL ,

Also, you use the FK provincia which is also not the same type as codigo.

Here's the script:

DROP TABLE IF EXISTS `Geo_Distrito`;
DROP TABLE IF EXISTS `Geo_Provincia`;
DROP TABLE IF EXISTS `Geo_Departamento`;

CREATE TABLE `Geo_Departamento` (
`codigo` int(10) unsigned NOT NULL COMMENT 'Codigo autogenerado',
`nombre` varchar(80) NOT NULL COMMENT 'Nombre del departamento',
`estado` int(10) unsigned NOT NULL COMMENT 'Estado de departamento',
PRIMARY KEY (`codigo`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Tabla de Departamentos';


CREATE TABLE `Geo_Provincia` (
`codigo` int(10) unsigned NOT NULL COMMENT 'Codigo autogenerado',
`departamento` int(10) unsigned NOT NULL,
`nombre` varchar(45) NOT NULL,
`estado` int(10) unsigned NOT NULL,
PRIMARY KEY (`departamento`,`codigo`) USING BTREE,
CONSTRAINT `FK_ProvinciaDepartamento` FOREIGN KEY (`departamento`) REFERENCES `Geo_Departamento` (`codigo`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Tabla de provincias del sistema.';

CREATE  TABLE IF NOT EXISTS `Geo_Distrito` (
`departamento` int(10) unsigned NOT NULL,
`provincia` int(10) unsigned NOT NULL,
`codigo` int(10) unsigned NOT NULL COMMENT 'Codigo autogenerado',
`nombre` VARCHAR(80) NULL ,
`estado` INT(10) NULL ,
PRIMARY KEY (`departamento`, `provincia`, `codigo`) ,
CONSTRAINT `FK_ProvinciaDistrito`  FOREIGN KEY (`departamento` , `provincia` )  REFERENCES `Geo_Provincia` (`departamento` , `codigo` )
)ENGINE = InnoDB;
like image 150
Book Of Zeus Avatar answered Sep 28 '22 07:09

Book Of Zeus