I have a table with usernames and IPs.
I need to get a list of the users who have similar IP -ignore last 3 or 2 or 1 digit(s)-
Example:
Count 190.200.210.180 and 190.200.210.60 as the same IP.
Count 205.50.4.30 and 205.50.4.197 as the same IP.
The field type of IPs is set as varchar and this is something I cannot change at the moment.
Currently I'm using :
SELECT GROUP_CONCAT( username ) names, IPs, COUNT( IPs ) AS Instances
FROM users
GROUP BY IPs
HAVING (COUNT(IPs) >1)
ORDER BY `Instances ` DESC
to get the users with the same IP.
Is it possible with the field of the IPs being set as varchar to make a select statement to group users with similar ips?
Thank you in advance for your help.
It means that you are dealing with what is known as a Class C network. In a Class C network, the first numbers of the IP address are the address of the network. You can have to 2,097,152 Class C network. The last number in the address are the individual PCs, laptops or other devices on the network.
To us, an IP address appears as four decimal numbers separated by periods. For example, you might use 204.132. 40.155 as an IP for some device in your network. You probably noticed that the four numbers making up an IP are always between 0 to 255.
An IP address has two parts: the network ID, comprising the first three numbers of the address, and a host ID, the fourth number in the address. So on your home network — 192.168. 1.1, for example – 192.168. 1 is the network ID, and the final number is the host ID.
IP addresses are expressed as a set of four numbers — an example address might be 192.158.1.38. Each number in the set can range from 0 to 255. So, the full IP addressing range goes from 0.0.0.0 to 255.255.255.255.
Try this:
SELECT
GROUP_CONCAT(username) AS names,
SUBSTRING_INDEX(IPs, '.', 3) AS IPs
COUNT(*) AS Instances
FROM
users
GROUP BY
SUBSTRING_INDEX(IPs, '.', 3)
HAVING
COUNT(*) > 1
ORDER BY
Instances DESC
The function SUBSTR_INDEX makes parsing an IP address an easy operation:
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(y.IPs,'.',1),'.',-1) a,
SUBSTRING_INDEX(SUBSTRING_INDEX(y.IPs,'.',2),'.',-1) b,
SUBSTRING_INDEX(SUBSTRING_INDEX(y.IPs,'.',3),'.',-1) c,
SUBSTRING_INDEX(SUBSTRING_INDEX(y.IPs,'.',4),'.',-1) d
FROM (SELECT ... FROM users) y
Using the aliased octets a,b,c,d as a base, you should be able to apply similar logic to your question and perform the octet-matching you desire...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With