-3
In my view the best way to "organize" is to use 1:m
, something like:
Sqls:
CREATE TABLE IF NOT EXISTS `clientes` (
`idclientes` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`nome` VARCHAR(45) NULL,
PRIMARY KEY (`idclientes`))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `emails` (
`idemails` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`email` VARCHAR(80) NULL,
`clientes_idclientes` INT UNSIGNED NOT NULL,
PRIMARY KEY (`idemails`),
INDEX `fk_emails_clientes_idx` (`clientes_idclientes` ASC),
CONSTRAINT `fk_emails_clientes`
FOREIGN KEY (`clientes_idclientes`)
REFERENCES `clientes` (`idclientes`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Data example:
INSERT INTO `clientes` (`nome`) VALUES
('João'),
('Maria'),
('Raul');
INSERT INTO `emails` (`idemails`, `email`, `clientes_idclientes`) VALUES
('[email protected]', 1),
('[email protected]', 1),
('[email protected]', 1),
('[email protected]', 2),
('[email protected]', 2);
If you want to display all customers, even those without emails use LEFT JOIN
:
SELECT
`clientes`.nome AS CLIENTE_NOME,
`emails`.email AS CLIENTE_EMAIL
FROM
`clientes` LEFT JOIN `emails` ON `emails`.clientes_idclientes = `clientes`.idclientes
WHERE 1;
Upshot:
CLIENTE_NOME | CLIENTE_EMAIL
==================================
João | [email protected]
João | [email protected]
João | [email protected]
Maria | [email protected]
Maria | [email protected]
Raul | NULL
If you only want to display customers who have emails use INNER JOIN
:
SELECT
`clientes`.nome AS CLIENTE_NOME,
`emails`.email AS CLIENTE_EMAIL
FROM
`clientes` INNER JOIN `emails` ON `emails`.clientes_idclientes = `clientes`.idclientes
WHERE 1;
Upshot:
CLIENTE_NOME | CLIENTE_EMAIL
==================================
João | [email protected]
João | [email protected]
João | [email protected]
Maria | [email protected]
Maria | [email protected]
Note that I used
LEFT JOIN
as only the table customers has no "restrictions", a row in the tableclientes
, if you want to create "loose" emails you will have to useFULL OUTER JOIN
To understand more about this I would like you to look at this great answer on the subject:
There’s something wrong with the image, there’s three O.o email tables
– rray