我在mysql中有这个查询:
SELECT DISTINCT phone.phone AS phone
FROM phone
INNER JOIN person ON person.id = phone.person_id
INNER JOIN locality ON locality.id = person.locality_id
INNER JOIN city ON city.id = locality.city_id
INNER JOIN department ON department.id = city.department_id
ORDER BY phone.id
LIMIT 10
EXPLAIN
TYPE TABLE TYPE POSIBLE_KEYS KEY LEN REF ROWS Extra SIMPLE department index PRIMARY PRIMARY 4 19 Using index; Using temporary; Using filesort SIMPLE city ref PRIMARY,fk_city_department fk_city_department 4 department.id 6 Using index SIMPLE locality ref PRIMARY,fk_locality_city fk_locality_city 4 city.id 1 Using index SIMPLE person ref PRIMARY,fk_person_locality fk_person_locality 5 locality.id 1596 Using index SIMPLE phone ref idx_phone,idx_phone_person,fk_phone_person fk_phone_person 9 person.id 1
表格电话有900000行,表人有70万行,表格部门,城市和地区各有250行。
" ORDER BY phone.id"的执行时间。是20.125秒,没有" ORDER BY phone.id"是0.001秒。
我需要ORDER BY,如何优化查询?
非常感谢...
答案 0 :(得分:0)
按字段排序是否有单独的索引?如果不是,则添加
答案 1 :(得分:0)
我找到了解决方案。它在0.300秒内完成50000行。
SELECT * FROM (SELECT phone.phone, phone.id AS pid FROM phone
INNER JOIN person ON person.id = phone.person_id
INNER JOIN locality ON locality.id = person.locality_id
INNER JOIN city ON city.id = locality.city_id
INNER JOIN department ON department.id = city.department_id
LIMIT 50000) AS tableaux
ORDER BY tableaux.pid