Question

I have two tables (SQL). One contains an IP address (table a), and the other contains two fields that represent the start an end of an IP range (table b - range_from and range_to). Neither one of these tables contain a common key to perform a join. I need to pull the country code from table b based on the ip address contained in table a; based on that ip address being in the range_from and range_to in table b. So, in other words I need to look to see which range (table B range) that IP from table a is in and pull the country code that corresponds. I have tried a few things but no luck. Any suggestions/ideas on how this can be accomplished?

table a

ip address name order# address country


255.65.28.214 Carlyle 7458214 45 N. East street United States

table b

range_from range_to country_code


192.168.52.69 192.168.75.11 US


192.0.78.23 192.0.78.99 CN

No correct solution

OTHER TIPS

Here is the formal method:

select a.*, b.country_code
from tablea a join
     tableb b
     on a.ipaddress between b.range_from and range_to;

If you care about performance there are more efficient ways. The most efficient is to create an index on tableb(range_from, range_to, country_code). Then if you assume there are no overlaps (because there aren't any) and there all your ip addresses in the first table match, then try:

select a.*,
       (select country_code
        from tableb b
        where b.range_from < a.ipaddress
        order by b.range_from desc
        limit 1
       ) as country_code
from tablea a;

Note that this uses limit to get one row. That depends on the database and might be top or fetch first 1 rows only or something else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top