Let\'s suppose I have a table T1 with people IDs and other stuff IDs, as the following
Table: T1
personID | stuffID
1 | 1
1 | 2
1
Try this
select personID from T1
group by personID
having count(distinct stuffID) >= (select count(*) from t2)
select personID
from T1
where stuffID in (select stuffID from t2)
group by personID
having count(distinct stuffID) = (select count(*) from t2)
I.e pick a person's stuffids which are in T2, count them (distinct only), and verify same number as in t2.
Using count
is an effective approach. Also, from the prospective of set theory, you can think about it in this way: for a valid personID, we shouldn't be able to find a stuffID in T2 but is not connect to this personID in T1. Therefore we can do it like this:
SELECT DISTINCT T1.personID
FROM T1
WHERE NOT EXISTS (
SELECT T2.stuffID
FROM T2
WHERE T2.stuffID NOT IN (
SELECT DISTINCT T1copy.stuffID
FROM T1 T1copy
WHERE T1copy.personID=T1.personID));
select personID from T1 group by personID having count(distinct stuffID) in (select count(distinct stuffID) from T2)
select count(distinct stuffID) from T2
<-- Would give the total number of distinct countIDs
group by personID having count(distinct stuffID)
<-- after grouping by personId , counting the number of stuffIds that personId has.
So both the counts should be equal to get the desired result.
If I understand correctly, you want to retrieve all the personID's from T1 that have all associated stuffID's found in T2.
You can break this up as follows: First of all, find all the T1 entries that match with a nested query
SELECT personID
FROM T1 WHERE stuffID IN (SELECT stuffID FROM t2)
Now you need to check which of the entries in this set contains ALL the stuffID's you want
GROUP BY personID
HAVING COUNT(DISTINCT stuffID) = (SELECT COUNT(stuffID) FROM t2)
and put it all together:
SELECT personID
FROM T1 WHERE stuffID IN (SELECT stuffID FROM t2)
GROUP BY personID
HAVING COUNT(DISTINCT stuffID) = (SELECT COUNT(stuffID) FROM t2)
HTH.