I have a database on which users has and belong to many "activities", and those activities are grouped by an activity_type:
Let's say i have a Users table
users
-------
id
name
.....
And an Activity table and type
activities
----------
id
name
activity_type_id
.
activity_types
--------------
id
name
And a join table
activities_users
------------------
user_id
activity_id
So the question is:
If i have activity_type ids 5 and 7, and need to make a query that brings the users who have been in activities of type 5 AND 7.
How can then this query be achieved?
Tried this:
SELECT users.id, users.name, users.email, users.phone FROM users
JOIN activities_users ON (
users.id = activities_users.user_id AND
(
activities_users.activity_id IN (SELECT activities.id FROM activities where activities.activity_type_id IN (5))
AND
activities_users.activity_id IN (SELECT activities.id FROM activities where activities.activity_type_id IN (7))
)
);
But realize i will have an empty set because activity_id on the 5th line will never be in one dataset and the other simultaneously.
Greetings!