Question

I have table with Static data (states(id, name)) AND table user_states(user_id, state_id)

How can i know if for some user (for example with id = '11') in table user_states are all recods from table states ?

If table states has 50 states, then check if user with id '11' has all 50 states.

I read about solution, how to check if data of table is identical :

SELECT ul.location_id
FROM bt_user_location ul
    JOIN bt_location_region llr ON (ul.location_id = llr.id)
WHERE ul.user_id= 11
UNION
SELECT lr.id
FROM bt_location_region lr

If Count Rows of this query is bigger then count of any of this tables, than tables are not identical. But if one table has identical rows to another table but not all, then this query will be not good.

Was it helpful?

Solution

Use Group By and Having.

SELECT
    ul.user_id
    count(1)
FROM user_states
GROUP BY ul.user_id
HAVING count(1) = 50

This will count the number of states that each user has and will only return the users that have 50 states. If you want to check a specific user, add a Where clause. If user with id 11 doesn't have all 50 states, no rows will be returned.

SELECT
    ul.user_id
    count(1)
FROM user_states
WHERE ul.user_id = 11
GROUP BY ul.user_id
HAVING count(1) = 50
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top