How do I find the user that has both a cat and a dog? How do I find the user that has both a cat and a dog? sql sql

How do I find the user that has both a cat and a dog?


Andomar - Unfortunately, writing the query like that will not necessarily always work as desired. Specifically, having 2 cats will cause the user to show up, and having 3 pets - say, 2 cats and a dog - will cause them to be excluded.
I don't know much about ActiveRecord, but the following is standard SQL syntax that would work:

SELECT users.idFROM UsersJOIN (SELECT user_id       FROM Pets      WHERE animal IN ('dog', 'cat')      GROUP BY user_id      HAVING COUNT(DISTINCT animal)) Pets  ON Pets.user_id = Users.id

This works differently than existing versions by counting the distinct "type" of pet ('cat' versus 'dog').


Use sub-selects to constrain the results:

User.joins(:pets).where(  'id IN (SELECT user_id FROM pets WHERE animal = ?) AND   id IN (SELECT user_id FROM pets WHERE animal = ?)',  'cat', 'dog')


The usual approach is to filter for cats OR dogs in the where clause. Then you group by on user_id, and demand that the resulting group having count(distinct pet.id) = 2.

I'm not sure how you express having in ActiveRecord; this post seems to contain a workaround.