To relate two columns of two different tables, first define who is part of who (son-father) for example:
If we have drinks and we must specify the type, we know then that drinks have types, they would be two tables, one of drinks and one of types, example:
- Drink: Orange Juice ---------------- Type: Juices
- Drink: Fruit Cocktail ------------- Type: Cocktail
Then we proceed to create two indexes of type unique in each of the tables, both in the child table and in the parent table, and point to the column that they want to relate.
Finally, a foreign key is created in the child table that refers to the column of the parent table from where the information needs to be acquired.
That's how my query is:
//Tabla tipoproductos
CREATE TABLE 'tipoproductos'
(
'idTipo' int(11) NOT NULL AUTO_INCREMENT,
'descripcionTipo' varchar(45) NOT NULL,
//Llaves o indexes
PRIMARY KEY ('idTipo'),
UNIQUE KEY 'tipoProd_idx' ('descripcionTipo')
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
CREATE TABLE 'productos'
(
'idProducto' int(11) NOT NULL AUTO_INCREMENT,
'codProducto' varchar(45) NOT NULL,
'descripcionProducto' varchar(45) NOT NULL,
'tipoProducto' varchar(45) NOT NULL,
'existenciaProducto' int(11) DEFAULT NULL,
'costoProducto' int(11) DEFAULT NULL,
'precioProducto' int(11) DEFAULT NULL,
//Llaves o indexes
PRIMARY KEY ('idProducto'),
UNIQUE KEY 'tipoProd_idx' ('tipoProducto'),
//Aqui la tabla hijo se relaciona
CONSTRAINT 'tipoProd_FK'
FOREIGN KEY ('tipoProducto')
REFERENCES 'tipoproductos' ('descripcionTipo')
ON DELETE NO ACTION
ON UPDATE NO ACTION
)ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
Thanks for your directions @Lucho T. you showed me the way to find the right answer.