In the ON
of JOIN
clause you can use the IN
operator and compare it to all the columns containing the id
of the collaborator. As you want to know the total time by sector, you also need to add GROUP BY
by sector:
SELECT colaboradores.setor, SUM(eventos.tempo) tempoTotal
FROM colaboradores
INNER JOIN eventos
ON colaboradores.id IN (
eventos.c1, eventos.c2, eventos.c3, eventos.c4, eventos.c5,
eventos.c6, eventos.c7, eventos.c8, eventos.c9, eventos.c10
)
GROUP BY colaboradores.setor
Result
+----------------+
|setor|tempoTotal|
|-----|----------|
| A| 1780|
| E| 2260|
| P| 2860|
| Q| 2860|
| X| 1660|
+----------------+
See working in Sql Fiddle .
Additional Information
Storing event contributors within the eventos
table is not ideal for normalization of data . This can cause a lot of problems, one of which is that you limit the amount of employees in an event by 10, if there is one day there, you will have a big job to do.
Since the relation of eventos
and colaboradores
is N:N
it is necessary to create a third table to reference.
But in this case, since the eventos
table only contains one column, you could do the inverse, one contributor per line and for each collaborator to store the time:
CREATE TABLE eventos(
id INT PRIMARY KEY AUTO_INCREMENT,
idcolaborador INT,
tempo INT,
CONSTRAINT fk_eventos_colaboradores FOREIGN KEY (idcolaborador) REFERENCES colaboradores (id)
);
In this way your SELECT
would look like this:
SELECT colaboradores.setor, SUM(eventos.tempo) tempoTotal
FROM colaboradores
INNER JOIN eventos
ON colaboradores.id = eventos.idcolaborador
GROUP BY colaboradores.setor
See working on Sql Fiddle .