Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a column contains ALL the values of another column - Mysql

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    |    3
    1    |    4
    2    |    1
    2    |    4
    3    |    1
    3    |    2

And another table T2 with just one column of stuffIDs

Table: T2
stuffID
   1  
   2  
   3  

The result that I would get, by a SELECT, is a table of peopleIDs who are connected with ALL the stuffIDs of T2.

Following the example the result would be only the id 1 (the personID 3 has no to appear even if all the stuffIDs it is associated are included in T2.stuffID).

like image 594
Marco Avatar asked Mar 09 '15 10:03

Marco


People also ask

How do you check if a column contains a value in MySQL?

Try this query: mysql_query(" SELECT * FROM `table` WHERE `column` LIKE '%{$needle}%' ");

How do I match two columns in MySQL?

Here's the generic SQL query to two compare columns (column1, column2) in a table (table1). mysql> select * from table1 where column1 not in (select column2 from table1); In the above query, update table1, column1 and column2 as per your requirement.

How do I check if two columns have the same value in MySQL?

Find duplicate values in multiple columns In this case, you can use the following query: SELECT col1, COUNT(col1), col2, COUNT(col2), ... FROM table_name GROUP BY col1, col2, ... HAVING (COUNT(col1) > 1) AND (COUNT(col2) > 1) AND ...


2 Answers

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.

like image 93
Eddy Avatar answered Sep 16 '22 22:09

Eddy


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.

like image 41
jarlh Avatar answered Sep 19 '22 22:09

jarlh