2

I need to compare two sets for equality.

I have an Employee table as

emp_id  | Name    
-----------------
1         Thomas 
2         John
3         Jeff     
.....
.....

and an Employee_Language table

Emp_id | Language   
------------------
1        English
1        French
2        Thai         
3        English
3        French
3        Chinese 
...
...

So I need to find all employees who knows a list of given languages for example 'English,French'

I know, using

select * from employee_language lng 
 where find_in_set(lng.language,'English,French') 

Will give a list of employees who either knows English or French .. How can I get employees who knows both ?

4

3 回答 3

7
WHERE language IN('x','y') GROUP BY emp_id HAVING COUNT (*) = 2 

(where '2' is the number of items in the IN clause)

So your whole query could be:

SELECT e.emp_Id
     , e.Name
  FROM Employee e
  JOIN Employee_Language l
    ON e.emp_id = l.emp_id
 WHERE l.Language IN('English', 'French')
 GROUP  
    BY e.emp_id 
HAVING COUNT(*) = 2

See this SQLFiddle

于 2013-07-08T10:39:55.517 回答
3

I just Improved the Accepted Answer by removing the constant (2) in the 'HAVING' clause and parameterized the criteria .. hope this help someone

set @lst = 'English,French,Chinese' ;

SELECT e.emp_Id,Name
 FROM Employee e
 JOIN Employee_Language l
 ON e.emp_id = l.emp_id
 WHERE FIND_IN_SET(l.Language,@lst)
 GROUP BY e.emp_id 
 HAVING COUNT(*) = (SELECT LENGTH(@lst) - LENGTH(REPLACE(@lst, ',', '')) AS `occurrences`)+1 ;

SQL Fiddle

于 2013-07-08T11:57:20.407 回答
2

The complete query:

select EMP.Name
from Employee EMP
where EMP.emp_id in 
(
   select EMP_L.emp_id
   FROM Employee_Language EMP_L
   EMP_L.emp_id
   WHERE Language in ('English','French')
   GROUP BY EMP_L.emp_id
   HAVING COUNT(*)=2
)
于 2013-07-08T10:45:00.890 回答