Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL where all in

Tags:

mysql

I have five tables in my database, users, jobs, qualifications, job_qualifications and users_qualification

I need to select all the staff that are qualified to carry out a particular job. It would be useful if there was a statement such as ALL IN so for example the query would be

SELECT user_id
FROM users_qualification
WHERE qualification_id ALL IN 
    (
        SELECT qualification_id 
        FROM job_qualifications 
        WHERE jobs_id = 1
    )
like image 772
bland_dan Avatar asked Jun 10 '12 19:06

bland_dan


2 Answers

If you know the number of qualifications that are required for the job, you can write this query:

SELECT uq.user_id
FROM users_qualification uq JOIN job_qualifications jq
    ON uq.qualification_id = jq.qualification_id
WHERE jq.jobs_id = 1
GROUP BY uq.user_id
HAVING COUNT(*) = {# of qualifications}

To find the number of qualifications, run:

SELECT COUNT(*)
FROM job_qualifications
WHERE jq.jobs_id = 1
like image 171
The Scrum Meister Avatar answered Sep 25 '22 19:09

The Scrum Meister


Expanding on The Scrum Meister's answer, you could do something like this:

SELECT
    distinct uq.user_id
FROM
    users_qualification uq
    JOIN job_qualifications jq ON uq.qualification_id = jq.qualification_id
WHERE
    jq.jobs_id = 1
GROUP
    BY uq.user_id
HAVING
    COUNT(*) = (SELECT COUNT(*) FROM job_qualifications jq2 WHERE jq2.job_id = jq.job_id)
like image 31
Aleks G Avatar answered Sep 24 '22 19:09

Aleks G