This query is really slow. Takes between 9 and 10 seconds...
SELECT DISTINCT a.*
FROM addresses a
LEFT JOIN contacts c
ON c.id = a.contact_id
LEFT JOIN organizations o
ON o.id = a.organization_id
ORDER BY c.last_name, c.first_name, o.name
LIMIT 0, 24
If I comment out the ORDER BY
clause the query runs much faster -- about 5 milliseconds. But I need the ORDER BY
to support paging of the search results. And the users need the addresses to be sorted by contact and organization.
Table structure
addresses
---------
id int NOT NULL
contact_id int # could be NULL
organization_id int # could be NULL
contacts
--------
id int NOT NULL
first_name varchar(255)
last_name varchar(255)
organizations
-------------
id int NOT NULL
name varchar(255)
They're all InnoDB tables.
I have these indexes on the contacts table:
KEY `idx_contacts_first_name` (`first_name`),
KEY `idx_contacts_last_name` (`last_name`),
KEY `idx_contacts_first_name_last_name` (`first_name`,`last_name`)
And on the organizations table:
KEY `idx_organization_name` (`name`)
Amount of data
Addresses: 22,271
Contacts: 17,906
Organizations: 8,246
DESCRIBE output
mysql> DESCRIBE
-> SELECT DISTINCT a.*
-> FROM addresses a
-> LEFT JOIN contacts c
-> ON c.id = a.contact_id
-> LEFT JOIN organizations o
-> ON o.id = a.organization_id
-> ORDER BY c.last_name, c.first_name, o.name
-> LIMIT 0, 24;
+----+-------------+-------+--------+---------------+---------+---------+--------------------------------------------+-------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+--------------------------------------------+-------+---------------------------------+
| 1 | SIMPLE | a | ALL | NULL | NULL | NULL | NULL | 22387 | Using temporary; Using filesort |
| 1 | SIMPLE | c | eq_ref | PRIMARY | PRIMARY | 4 | contactdb_v2_development.a.contact_id | 1 | Distinct |
| 1 | SIMPLE | o | eq_ref | PRIMARY | PRIMARY | 4 | contactdb_v2_development.a.organization_id | 1 | Distinct |
+----+-------------+-------+--------+---------------+---------+---------+--------------------------------------------+-------+---------------------------------+
3 rows in set (0.00 sec)