Match each variable passed in MYSQL IN()
Basically I have the following query:
SELECT DISTINCT users.ID, users.name
FROM users
INNER JOIN usersSkills ON users.ID = usersSkills.userID
INNER JOIN usersLanguages ON users.ID = usersLanguages.userID
WHERE activated = "1"
AND type = "GRADUATE"
AND usersSkills.skillID IN(2, 21)
AND usersLanguages.languageID IN(2, 22)
I need to match the skillID an开发者_Python百科d languageID to each parameter passed in the IN() function at the moment on each of those it will serve up a result if either parameter is found.
So essentially i want to only see results if the skill ID of 2 AND 21 are found on the skills table and the same idea for the languages...
Use a GROUP BY (this will also eliminate the need for SELECT DISTINCT) to get an aggregate count and a HAVING clause to make sure the count of distinct elements returned matches the number of elements you're searching for.
SELECT users.ID, users.name
FROM users
INNER JOIN usersSkills ON users.ID = usersSkills.userID
INNER JOIN usersLanguages ON users.ID = usersLanguages.userID
WHERE activated = "1"
AND type = "GRADUATE"
AND usersSkills.skillID IN(2, 21)
AND usersLanguages.languageID IN(2, 22)
GROUP BY users.ID, users.name
HAVING COUNT(DISTINCT usersSkills.skillID) = 2
AND COUNT(DISTINCT usersLanguages.languageID) = 2
精彩评论