且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查一列是否包含另一列的所有值-MySQL

更新时间:2022-12-10 08:26:57

如果我正确理解,您希望从T1中检索所有在T2中找到所有关联的stuffID的personID.

If I understand correctly, you want to retrieve all the personID's from T1 that have all associated stuffID's found in T2.

您可以按以下步骤将其分解: 首先,找到所有与嵌套查询匹配的T1条目

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)

现在,您需要检查该集合中的哪些条目包含所需的所有stuffID.

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)

将它们放在一起:

SELECT personID 
FROM T1 WHERE stuffID IN (SELECT stuffID FROM t2)
GROUP BY personID
HAVING COUNT(DISTINCT stuffID) = (SELECT COUNT(stuffID) FROM t2)

HTH.