i got this tabels
Users:
id name
1 | tom
2 | jim
3 | bob
User_Has_Toys
user_id toy_id
1 | 2
1 | 3
1 | 4
2 | 2
2 | 4
3 | 4
Toy
id name
1 | toy1
2 | toy2
3 | toy3
4 | toy4
5 | toy5
and i make query
SELECT u.id FROM Users u
LEFT JOIN User_Has_Toys uht ON (u.id = uht.user_id)
LEFT JOIN Toy t ON t.id = uht.toy_id
WHERE t.id IN ('2', '4')
and i get all users
but i need only users with id 1 and 2
could some one help me?
One method to check if a user has multiple specific rows in another table is to filter for those rows and see if count is correct. So for instance, if we count the number of rows in User_Has_Toys for a specific user id and filtering for toys 2 and 4, we should get a count of 2 if and only if the user has both toys 2 and 4 (NOTE: assuming duplicate toy entries are not allowed). The query would look something like this:
Demo: http://sqlize.com/6yU3OlU2pD
You could also get the same result with a minor modification to your original query by grouping by the user id and checking that the toy count is exactly 2:
Demo: http://sqlize.com/7nTYZbJKsn