我有一个大约〜 84mb 的MySQL数据库。以下查询:
SELECT
`reservations`.`id`
FROM
`reservations`
INNER JOIN `reservation_room`
ON `reservation_room`.`reservation_id` = `reservations`.`id`
LEFT JOIN `users`
ON `reservations`.`user_id` = `users`.`id`
INNER JOIN `rooms`
ON `reservation_room`.`room_id` = `rooms`.`id`
INNER JOIN `stories`
ON `rooms`.`story_id` = `stories`.`id`
INNER JOIN `hotels`
ON `stories`.`hotel_id` = `hotels`.`id`
INNER JOIN `neighbourhoods`
ON `hotels`.`neighbourhood_id` = `neighbourhoods`.`id`
INNER JOIN `cities`
ON `cities`.`id` = `neighbourhoods`.`city_id`
GROUP BY `reservations`.`id`
ORDER BY `reservations`.`created_at` DESC
LIMIT 30
OFFSET 0
执行需要大约4到700秒。 reservations
表有48k记录,reservation_room
有191k记录。这个查询经常执行,它使得mysql进程在CPU上变得很难:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
5021 mysql 20 0 755m 385m 8596 S 748.7 1.2 5353:58 mysqld
我该怎么做才能加快查询速度,或者至少不会让整个mysql服务器疯狂?
上述查询的 EXPLAIN
:
98%的执行时间是Copying to temp table
。