Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select grouping where all the elements meet the condition

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!

like image 483
Nazareno Lorenzo Avatar asked Nov 28 '11 05:11

Nazareno Lorenzo


People also ask

How do you GROUP BY based on conditions?

SQL GROUP BY Syntax “GROUP BY column_name1” is the clause that performs the grouping based on column_name1. “[,column_name2,…]” is optional; represents other column names when the grouping is done on more than one column. “[HAVING condition]” is optional; it is used to restrict the rows affected by the GROUP BY clause.

Which command is used to place conditions on groups?

We know that WHERE clause is used to place conditions on columns but what if we want to place conditions on groups? This is where HAVING clause comes into use. We can use HAVING clause to place conditions to decide which group will be the part of final result-set.

Can we use SELECT * with GROUP BY?

You can use a SELECT command with a GROUP BY clause to group all rows that have identical values in a specified column or combination of columns, into a single row.

What does count (*) do in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.


1 Answers

Give this a shot. Let me know if I'm missing the mark on what exactly it is you're looking for.

select animal
from pets
group by animal
having animal not in
(
select animal
from pets
where name not in ('homer','bart','marge','lisa','maggie')
group by animal
)

It sounds obvious when you say it, but the trick to getting only the results you want is sometimes to first create a query that gets all the results you don't want and then just exclude them.

like image 143
Brandon Moore Avatar answered Oct 05 '22 23:10

Brandon Moore