I have 2 tables in my mySQL database.
First table is isp:
isp_ip_address | isp_name
-------------------------
157.55.33.0 | isp_3
157.55.0.0 | isp_1
193.219.9.0 | isp_2
65.55.213.0 | isp_4
195.182.85.226 | isp_5
78.58.5.117 | isp_6
78.58.5.0 | isp_7
Second table is user_stats:
uid | lastlogin_ip | lastlogin
------------------------------
111 | 78.58.83.111 | 2013-03-12
132 | 78.58.5.117 | 2013-03-12
258 | 195.182.85.226 | 2013-03-14
165 | 157.55.33.78 | 2013-03-12
822 | 65.55.213.216 | 2013-03-15
523 | 157.55.35.38 | 2013-03-12
.....
And so on.
I need to compare users lastlogin_ip to isp_ip_address and in a new table insert uid, lastlogin_ip and isp_name. I need to compare ip_address like this: if full lastlogin_ip equals isp_ip_address then stop searching and write isp_name, if they don't match, I need to compare firdt 3 parts of IP addresses and do the same, and if 3 parts don't match, I need to compare 2 parts of IP addresses and do the same.
I tried the following SQL code:
SELECT
user_stats.`uid`,
user_stats.`lastlogin_ip`,
isp.`isp`,
FROM
stats.`user_stats`
LEFT JOIN stats.`isp`
ON(
IF(
isp.isp_ip_address LIKE user_stats.`lastlogin_ip`,
isp.isp_ip_address LIKE user_stats.`lastlogin_ip`,
IF(
SUBSTRING_INDEX(isp.isp_ip_address,'.',-1) LIKE SUBSTRING_INDEX(user_stats.`lastlogin_ip`,'.',-1),
IF(
SUBSTRING_INDEX(SUBSTRING_INDEX(isp.isp_ip_address,'.',3),'.',-1) LIKE SUBSTRING_INDEX(SUBSTRING_INDEX(user_stats.`lastlogin_ip`,'.',3),'.',-1),
IF(
SUBSTRING_INDEX(SUBSTRING_INDEX(isp.isp_ip_address,'.',2),'.',-1) LIKE SUBSTRING_INDEX(SUBSTRING_INDEX(user_stats.`lastlogin_ip`,'.',2),'.',-1),
SUBSTRING_INDEX(isp.isp_ip_address,'.',1) LIKE SUBSTRING_INDEX(user_stats.`lastlogin_ip`,'.',1),
NULL),
SUBSTRING_INDEX(isp.isp_ip_address,'.',2) LIKE SUBSTRING_INDEX(user_stats.`lastlogin_ip`,'.',2)),
SUBSTRING_INDEX(isp.isp_ip_address,'.',3) LIKE SUBSTRING_INDEX(user_stats.`lastlogin_ip`,'.',3))));
This code compares parts of IP addresses but it duplicates rows, which means that if it finds 3 equal parts and 2 equal parts, it writes the same row two times with different isp_name values.
Could you give me a hint how should I edit this code to work as it should? Any help would be appreciated!