Mysql relationship between two tables

Asked

Viewed 61 times

0

Good morning, for a work record I was given the following exercise:

Imagine the following scenario. It is intended to create a database that supports the control of stocks. Each product belongs to a family, for example: A block of A4 sheets belongs to the office material family. Using phpmyadmin create the tables needed to support this scenario.

I have created the following tables:

CREATE TABLE `produtos` (
  `id_produto` int(11) NOT NULL AUTO_INCREMENT,
  `produto` varchar(11) NOT NULL,
  `qtd_stock` varchar(11) NOT NULL,
   PRIMARY KEY (`id_produto`)
)

CREATE TABLE `familia` (
  `id_familia` int(11) NOT NULL AUTO_INCREMENT,
  `familia` varchar(80) NOT NULL,
   PRIMARY KEY (`id_familia`),
)

Can someone give me a help of what relationships do ?

1 answer

0


This could be a relationship 1..n (one for many), which a product must be associated with only one family and a family may have one or more products. In this case, you need to insert a foreign key into the table produtos referring to which family he belongs to.

ALTER TABLE `produtos` ADD id_familia_fk int(11) NOT NULL;
ALTER TABLE `produtos` ADD CONSTRAINT `fk_familia` 
FOREIGN KEY ( `id_familia_fk` ) REFERENCES `familia` ( `id_familia` ) ;

However, nothing prevents the product from being associated with more than one family (relationship n..n). Therefore, if this is the case, it will be necessary to create a table containing foreign key from both tables família and produtos. But I believe for you, the first case (1..n) answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.