Connecting Tech Pros Worldwide Forums | Help | Site Map

mysql counting occurances in a table

Member
 
Join Date: Sep 2008
Posts: 73
#1: 3 Weeks Ago
Hi,

Here is a table that I am working with:

PERSON | HAS
--------------------------------------------------------
John | Laptop
John | Cell Phone
John | PS3
Sally | Cell Phone
Sally | Laptop
Jane | Laptop


I want my query to return the set of people who own all 3 items (Laptop, Cell Phone, PS3)....

So in this example above, the only name that should come up is "John"

One catch, this has to be dynamic, so future items can be added to the list. Basically, it's suppose to count all items in the list and see if a person owns all of them.

Please help.

RedSon's Avatar
Site Moderator
 
Join Date: Jan 2007
Location: America
Posts: 3,393
#2: 3 Weeks Ago

re: mysql counting occurances in a table


Check out the count() function.
Member
 
Join Date: Sep 2008
Posts: 73
#3: 3 Weeks Ago

re: mysql counting occurances in a table


Expand|Select|Wrap|Line Numbers
  1. SELECT person
  2. FROM my_table
  3. GROUP BY person
  4. HAVING Count( person ) = Count( has )
this is what i have right now and no luck.
RedSon's Avatar
Site Moderator
 
Join Date: Jan 2007
Location: America
Posts: 3,393
#4: 3 Weeks Ago

re: mysql counting occurances in a table


try something like :

count (has) from my_table where person = john.
Member
 
Join Date: Feb 2009
Posts: 57
#5: 3 Weeks Ago

re: mysql counting occurances in a table


You can try something like:

Expand|Select|Wrap|Line Numbers
  1. SELECT person FROM my_table GROUP BY person HAVING COUNT(has) = (SELECT COUNT(DISTINCT has) FROM my_table);

Hope this could help.

Thanks,
Lauren
Reply


Similar MySQL Database bytes