1

I have two tables. The ipaddress range table is in the following format:

ip_start BIGINT
ip_end BIGINT
country VARCHAR

(IP addresses have been converted to a number)

The second table contains the order details and the users ip_address also in the same number format.

I am trying to return the orders table together with the country of the ipaddress.

Doing the following join works, but the query takes several minutes on about 5000 rows.

SELECT *  FROM  orders o
LEFT JOIN iplookup ip
  ON o.ip_address >=  ip.ip_start AND
     o.ip_address <= ip.ip_end

How can I improve the performance of this query?

EXPLAIN responds with:

id select_type table type possible_keys key  key_len ref rows  Extra
1  SIMPLE      o     ALL  NULL          NULL NULL NULL   45775 Using where
1  SIMPLE      ip    ALL  ip_start,     NULL NULL NULL   140712
                          ip_end,
                          star_end_idx
8
  • 1
    What does explain select... says for the above query ? May 21, 2015 at 8:29
  • @AbhikChakraborty It just tells me that both are simple queries and how many rows there are per table. The ipaddress table is quite large obviously. Containing some 140k entries. May 21, 2015 at 8:44
  • You are missing indexes for sure, the query looks good. Add the following indexes after taking a backup of the tables alter table orders add index ip_address_idx(ip_address); alter table iplookup add index star_end_idx(ip_start,ip_end) May 21, 2015 at 8:48
  • @AbhikChakraborty Thanks, but they are all indexed. Still takes around 5 minutes. May 21, 2015 at 8:56
  • please post the explain result into the question, without seeing the result hard to say anything. May 21, 2015 at 9:17

3 Answers 3

0

I'm Not sure but I used to read some article about this

If I remember you should use WHERE clause to filter table you want before join

For Example

SELECT * 
FROM orders o 
LEFT JOIN (
     SELECT *
     FROM iplookup ip
     WHERE ip.start BETWEEN ......... AND ...........
) ip  ON o.idColoum = ip.idCol
0

IPv4 needs 32 bits (INT UNSIGNED); IPv6 needs 128 bits (BINARY(16)); BIGINT is not appropriate.

o.ip_address >= ip.ip_start AND
o.ip_address <= ip.ip_en

cannot be optimized by any subquery or INDEX.

You have no overlapping ip_start/end ranges, correct? In that case, my blog on ip ranges covers how to do the task much more efficiently than what you have encountered. It requires re-designing your table to have only ip_start values, and the blog provides the Stored Routines necessary for IPv4 and for IPv6.

0

After some more testing I have realized that the query actually executes very quickly. This seems to be an issue with phpMyAdmin rendering the data as the results are fast using the MySql console.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.