Let's say I have two tables:
Table foo
===========
id | val
--------
01 | 'a'
02 | 'b'
03 | 'c'
04 | 'a'
05 | 'b'
Table bar
============
id | class
-------------
01 | 'classH'
02 | 'classI'
03 | 'classJ'
04 | 'classK'
05 | 'classI'
I want to return all the values of foo and bar for which foo exists in more than one distinct bar. So, in the example, we'd return:
val | class
-------------
'a' | 'classH'
'a' | 'classK'
because although 'b' exists multiple times as well, it has the same bar value.
I have the following query returning all foo for which there are multiple bar, even if the bar are the same:
select distinct foo.val, bar.class
from foo, bar
where foo.id = bar.id
and
(
select count(*) from
foo2, bar2
where foo2.id = bar2.id
and foo2.val = foo.val
) > 1
order by
va.name;