Hello, I played your scenario here! and I set up what you might be wanting:
CREATE TABLE Funcionario
(
Id INT NOT NULL AUTO_INCREMENT,
Nome VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE Dependente
(
Id INT NOT NULL AUTO_INCREMENT,
FuncionarioId INT NOT NULL,
Nome VARCHAR(100) NOT NULL,
PRIMARY KEY (Id),
FOREIGN KEY (Id) REFERENCES Funcionario(id)
);
CREATE TABLE Dependente_Has_Funcionario
(
Id INT NOT NULL AUTO_INCREMENT,
FuncionarioId INT NOT NULL,
DependenteId INT NOT NULL,
PRIMARY KEY (Id)
);
insert into Funcionario (Id,Nome) values ('101','Rodrigo Mendez');
insert into Funcionario (Id,Nome) values ('102','Marco Ciciliano');
insert into Funcionario (Id,Nome) values ('103','Paulo Guerra');
insert into Funcionario (Id,Nome) values ('104','Renato Teixeira');
insert into Funcionario (Id,Nome) values ('105','Antonio Marcos');
insert into Dependente (Id,FuncionarioId,Nome) values ('101','101','Mauricio Filho');
insert into Dependente (Id,FuncionarioId,Nome) values ('102','101','Arnaldo Filho');
insert into Dependente (Id,FuncionarioId,Nome) values ('103','102','Jenival Filho');
insert into Dependente (Id,FuncionarioId,Nome) values ('104','102','Walter Filho');
insert into Dependente (Id,FuncionarioId,Nome) values ('105','105','Nataly Filho');
insert into Dependente_Has_Funcionario (Id,FuncionarioId,DependenteId) values ('101','101','101');
insert into Dependente_Has_Funcionario (Id,FuncionarioId,DependenteId) values ('102','101','102');
insert into Dependente_Has_Funcionario (Id,FuncionarioId,DependenteId) values ('103','102','103');
You can do using 2 tables with the "GROUP BY" clause with a "COUNT" between Employee and Dependent:
See on Sqlfiddle
SELECT
a.Nome,
COUNT(*) Dependentes
FROM
Funcionario a,
Dependente b
WHERE
a.id = b.FuncionarioId
GROUP BY
a.Nome;
or by what I noticed using the third table that is Funcio related to the table 'dependente_has_funcionario'
See on Sqlfiddle
SELECT
a.Nome,
COUNT(*) Dependentes
FROM
Funcionario a,
Dependente_Has_Funcionario b
WHERE
a.id = b.FuncionarioId
GROUP BY
a.Nome;
I hope I helped!
Oks!
I edited your answer by adding links to the Sqlfidlle where the result of querys can be viewed.
– ramaral