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.