views:

120

answers:

2

I have a table with an ip address column. I would like to find the top five addresses which are listed.

Right now I'm planning it out the following:

  1. Select all distinct ip addresses
  2. Loop through them all saying count(id) where IP='{ip}' and storing the count
  3. List the top five counts.

Downsides include what if I have 500 ip addresses. That's 500 queries I have to run to figure out what are the top five.

I'd like to build a query like so

select ip from table where 1 order by count({distinct ip}) asc limit 5
+3  A: 
select IP, count(IP) as IPCount from TABLE
group by IP
order by IPCount DESC
Limit 5

There is :)

pojomx
+3  A: 
select ip, count(*)
from table
group by ip
order by count(*) desc limit 5
RedFilter
Excellent, thanks. Though can you explain a bit better how the `group by` works? Remove it and I only get the same ip and count repeated five times.
Josh K
@Josh: Imagine you are dealt a hand of cards and you were asked to count how many red vs. black cards there were. In order to do this, you are grouping them by colour. You could also be asked what is the highest or lowest red card, and again, you would group by colour and then determine the highest and lowest. This is what the above query is doing, but it is grouping by `ip address` instead of colour.
RedFilter
Nice explanation, thanks!
Josh K