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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With