MariaDB/MMySQL在一个范围内连接表



我有一个表,其中包含一个IP地址:

create table login_history
(
id         int auto_increment primary key,
ip         int unsigned,
created    datetime(6)  not null,
user_id    int unsigned not null,
);

和另一个具有IP范围的表:

create table ip2location
(
ip_from      int unsigned not null primary key,
ip_to        int unsigned null,
country_code char(2)      null,
)

我正试图用下面的";关于";表示

select * from login_history
left join ip2location_db1  on
ip2location_db1.ip_from <= login_history.ip_int and ip2location_db1.ip_to >= login_history.ip_int

它运行得很好,但速度很慢。如何提高这样一个查询的性能?我已经在两个表的IP列上添加了索引。

谢谢你的帮助。祝你今天愉快!

一种可能性是:

select lh.*,
(case when ip.ip_from <= lh.ip_int then ip.country)
from (select lh.*,
(select ip.ip_from
from ip2location_db1 ip
where ip_to >= lh.ip_int
order by ip_to
limit 1
) as ip_to
from login_history lh
) lh left join
ip2location_db1 ip
on ip.ip_to = lh.ip_to;

这样就可以利用ip2location_db1(ip_to)上的索引。

最新更新