Actually, your primary key have little sense in terms of such range query. It only indicates unique pairs for <from_ip, to_ip>
tuple - thus, MySQL will not be able to use that index with such range comparisons.
Unless you're running some query that involves both parts of your primary key, it will have no effect (well, actually, MySQL also will use it - when selection condition uses left-subset of compound index, but that's not your case). For example, this will use primary key:
-- @x and @y are derived from somewhere else
SELECT * FROM inetnum WHERE from_ip=@x && to_ip=@y
In your case, compound key may be primary key, yes, but it's only benefit will be - to provide uniqueness. So, you can leave it as it is, or create surrogate id
primary key (replacing current primary key with UNIQUE
constraint).
One of possible solutions to improve situation could be - create single-column keys for from_ip
and to_ip
. Since they are integers, there's a good chance for high cardinality, that result indexes will have. However, MySQL can use only one index, and, therefore, you'll lose 'half' of range efficient comparison.
Also you should remember, that if greater-than (or less-than) comparison will affect too many rows, MySQL will not use index as well (since, obviously, there's no sense in that because there are too much rows to select).
And - yes, avoid using functions in WHERE
clause. I'm not saying that MySQL will always loose index usage in such case (but most likely, it will loose it in most cases) - but think about overhead that will cause function call. Even if it's little - you can always get rid of it via passing correct value, formed by your application.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…