Home > Database > Mysql Tutorial > How to Find Person IDs Associated with All Stuff IDs in MySQL?

How to Find Person IDs Associated with All Stuff IDs in MySQL?

Patricia Arquette
Release: 2024-12-29 10:27:13
Original
682 people have browsed it

How to Find Person IDs Associated with All Stuff IDs in MySQL?

Check if a Column Contains All Values of Another Column in MySQL

Problem:

Suppose you have two tables, T1 and T2, with columns representing people IDs and stuff IDs. How can you determine which person IDs are associated with all the stuff IDs in T2?

Solution:

To find the person IDs that have all associated stuff IDs found in T2, follow these steps:

  1. Use a nested query to select the person IDs from T1 that match any stuff ID in T2:
SELECT personID
FROM T1
WHERE stuffID IN (SELECT stuffID FROM t2)
Copy after login
  1. Group the results by person ID and check which entries contain all the stuff IDs in T2:
GROUP BY personID
HAVING COUNT(DISTINCT stuffID) = (SELECT COUNT(stuffID) FROM t2)
Copy after login
  1. Combine these queries to get the final result:
SELECT personID
FROM T1
WHERE stuffID IN (SELECT stuffID FROM t2)
GROUP BY personID
HAVING COUNT(DISTINCT stuffID) = (SELECT COUNT(stuffID) FROM t2)
Copy after login

This query will return the person IDs that have all associated stuff IDs specified in T2. In the example provided, the result would be person ID 1.

The above is the detailed content of How to Find Person IDs Associated with All Stuff IDs in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template