I’m having some troubles with a MySQL Query.
I want to select all the elements from a table, grouping from a certain column, BUT only retrieve those where ALL the elements in the group matches the WHERE clause.
For example, I have a table called “pets” with 3 columns:
Id| animal | name
1 | dog | marge
2 | dog | homer
3 | cat | marge
4 | cat | lenny
5 | rabbit | homer
5 | rabbit | carl
6 | rabbit | marge
And I want to pick all the animals where ALL his group members have name IN(‘homer’,’bart’,’marge’,’lisa’,’maggie’)
If you can’t understand my question, let me know. Thanks!
Put another way, it’s ‘Select all the animals for whom the number of corresponding names not matching the condition
IN ('homer','bart','marge','lisa','maggie')is0’.So it could be implemented also like this:
This expression
results in either
1orNULL, consequently causingCOUNTeither to count the corresponding occurrence ofnameor to omit it. (As to whyOR NULLis there and how the entire expression works, I’ll refer you to this question: Why do I need "OR NULL" in MySQL when counting rows with a condition.)As you can see, you could alternatively use
SUMto do the same, and the expression forSUMis apparently shorter, as theOR NULLpart isn’t needed there. I usually preferCOUNT()toSUM()when I need to count things, as opposed to adding up arbitrary values. But, to my knowledge, there’s no advantage of one before the other, so which function to use is up to your personal preferences/tastes.