从具有多个连接的表中进行简单选择需要很长时间才能执行

时间:2018-02-15 14:25:27

标签: mysql join

我有一个大约〜 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

enter image description here

98%的执行时间是Copying to temp table

0 个答案:

没有答案