Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - How to select rows which have the same multiple values

I'll start with a simplified example of my table:

+-----+----------+
|Name |Teaches   |
+-----+----------+  
|Dave |Science   |
+-----+----------+  
|Dave |History   |
+-----+----------+  
|Alice|History   |
+-----+----------+  
|Alice|Literature|
+-----+----------+  
|Alice|Science   |
+-----+----------+  
|John |History   |
+-----+----------+

I'm trying to select those people who also teach the same classes as Dave. (In this case, Alice). I'm thinking of using a cursor to go through Dave's courses and selecting those people who teach the same course and intersecting the results, but I'd like to know if there is a better (simpler) way.

like image 227
user3529379 Avatar asked Jan 10 '18 02:01

user3529379


1 Answers

Here is one method:

select t.name
from t join
     t td
     on td.teaches = t.teaches 
where td.name = 'Dave'
group by t.name
having count(*) = (select count(*) from t where t.name = 'Dave');
like image 62
Gordon Linoff Avatar answered Nov 15 '22 10:11

Gordon Linoff