這個查詢真的很慢。我注意到9和10秒之間......任何方式來加快此查詢?
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
如果註釋掉ORDER BY
子句的查詢運行得更快 - 約5毫秒。但我需要ORDER BY
來支持分頁搜索結果。用戶需要通過聯繫和組織對地址進行排序。
表結構
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)
他們都是InnoDB表。
我對接點表這些指標:
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`)
而且在組織表:
KEY `idx_organization_name` (`name`)
數據量
Addresses: 22,271
Contacts: 17,906
Organizations: 8,246
說明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)
你是什麼意思的「做你的訂單和分頁在該級別。」?您是否建議在從數據庫中檢索數據後,在應用程序代碼中進行排序? – sleske 2009-10-22 23:42:36
是的。對於一個大約20,000行的數據集,這個數據集可能不會發生太大的變化,所以對數據進行抽取,分類和緩存是有意義的。 – 2009-10-22 23:56:32
是的,我想我會用這樣的東西。將所有記錄提供給分頁可能看起來很奇怪,但如果不這樣做會導致令人痛苦的UI複雜性。 – Ethan 2009-10-24 00:55:21