Question

I've been trying to figure this out for a while now, but I had no success, partialy because I don't deal with SQL all that much. But I started to work on some pet project, so I would need help from someone more experianced in ways of relational thinking :)

Supose we have 3 tables :

worker(id,...)
worker_project(worker_id,project_id,...)
project(id,...)

And that worker_id and project_id are part of a composite primary key of the worker_project table. So any worker could be involved in some number of projects, and any project would have some number of workers bound to itself. So, for example :

John Doe -> project1,project2,project3,project4

Marry jane -> project2,project4

Apu Humuhumunukunukuapua -> project1,project4,project5

Given an array of projects

(e.g. id's of project1,project2,project4,project5)

What I want to accomplish is to find ALL WORKERS WHOSE SET OF RELATED PROJECTS IS COMPLETELY CONTAINED IN GIVEN ARRAY OF PROJECT IDs.

In this example, that would be Marry and Apu, because John also works on project3, and it's id is not given.

I guess it is similar to this question, but I couldn't get it to work for some reason.

Was it helpful?

Solution

If I'm not misunderstood your question, this should work:

select w.* 
from worker w, (
    select worker_id, count(*) cnt
    from worker_project
    where project_id in (1,4,5)
    group by worker_id
) w_count,  (
    select worker_id, count(*) cnt_all
    from worker_project
    group by worker_id
) w_count_all
where w.worker_id=w_count.worker_id and 
      w.worker_id=w_count_all.worker_id and
      w_count.cnt=w_count_all.cnt_all

OTHER TIPS

I think you could accomplish this with an anti-JOIN:

SELECT w.id
FROM worker w
/* See if they have a project outside our list */
LEFT JOIN worker_project wp
  ON wp.worker_id = w.id AND wp.project_id NOT IN (1, 2, 4, 5)
/* Make sure they have a project */
JOIN worker_project wp2
  ON wp2.worker_id = w.id
/* Only include those without a project outside the list */
WHERE wp.worker_id IS NULL
GROUP BY w.id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top