Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
02-21-2012, 04:34 AM #1
- Join Date
- Dec 2009
- Hong Kong
- Thanked 0 Times in 0 Posts
how to group and count with wildcards ?
I have a table with IP numbers and like to group and count them in 255er lots.
// data in table qtt ip 1 22.214.171.124 5 126.96.36.199 1 188.8.131.52 3 184.108.40.206 8 220.127.116.11 1 18.104.22.168 // wanted output: 1 99.198.98.* 6 99.198.127.* 3 99.198.125.* 9 99.198.119.*
02-21-2012, 06:31 AM #2
A couple of ways it could be done. The best way, from a performance perspective, would probably be to add another field to the table, which is the UNSIGNED INT version of the IP address. You could calculate that (e.g, in PHP code) at the same time you insert the text version.
And then you would just do
That will be faster than playing with the string form.Code:SELECT FLOOR(ipAsInteger/256) AS ipDiv256, COUNT(*) AS howmany FROM table GROUP BY FLOOR(ipAsInteger/256) ORDER BY 1
But if you don't do this often, you could certainly do it from the string form:
You see it?Code:SELECT LEFT( ipaddress, LENGTH(ipaddress) - INSTR(REVERSE(ipaddress),'.') ) AS left3, COUNT(*) AS howmany FROM table GROUP BY LEFT( ipaddress, LENGTH(ipaddress) - INSTR(REVERSE(ipaddress),'.') ) ORDER BY 1
REVERSE of (example) '22.214.171.124' is '73.98.981.99'
INSTR( '73.98.981.99', '.' ) is 3
LENGTH('126.96.36.199') is 12
12 - 3 is 9
LEFT('188.8.131.52',9) is '99.198.98'
REVERSE of (example) '184.108.40.206' is '122.98.981.99'
INSTR( '122.98.981.99', '.' ) is 4
LENGTH('220.127.116.11') is 13
13 - 4 is 9
LEFT('18.104.22.168',9) is '99.198.98'
and so on.
Fair warning: If you do ORDER BY 1 (that is, ORDER BY the first 3 groups of the ip address), you *WILL* find that (for example)
will come before
just for example. Because it will be *string* ordering, not numeric ordering. This is another reason you might consider adding an ipAsInteger field to your table.
Be yourself. No one else is as qualified.