需要帮助优化mysql查询

时间:2014-11-07 16:07:05

标签: mysql sql join

我正在编写一个mysql查询,如下所示

SELECT `user_master`.`first_name`, 
       `city_name`, 
       `user_master`.`last_name`, 
       `user_master`.`user_master_id`, 
       `account_management_master`.`account_name`, 
       `donation_receipt_info`.`receipt_temple_id`, 
        date(dt) AS dt, 
       SUM(`donation_receipt_info`.`amount`) AS amount 
FROM (`donation_receipt_info`) 
JOIN `donation_receipt_master` ON donation_receipt_master`.`receipt_id`=`donation_receipt_info`.`receipt_id`
JOIN `account_management_master` ON `account_management_master`.`account_id`=`donation_receipt_info`.`account_id`
JOIN `user_master` ON `user_master`.`user_master_id`=`donation_receipt_master`.`user_master_id`
JOIN `user_address_info` ON `user_address_info`.`user_master_id`=`user_master`.`user_master_id`
JOIN `city_master` ON `city_master`.`city_id`=`user_address_info`.`city_id`
WHERE `donation_receipt_info`.`temple_id` = '1' 
GROUP BY `donation_receipt_info`.`receipt_id`, 
         `donation_receipt_info`.`account_id`

表donation_receipt_info和master有大约42k的结果,查询正在采取大约5到6分钟的时间在mysql本身执行。 有人可以帮我优化查询,任何帮助或建议将非常有帮助 感谢。

1 个答案:

答案 0 :(得分:1)

首先,您的查询无法阅读。您应该格式化它并学习使用表别名:

SELECT um.first_name, city_name, um.last_name, um.user_master_id, amm.account_name, 
       dri.receipt_temple_id, date(dt) AS dt, SUM(dri.amount) AS amount
FROM donation_receipt_info dri JOIN
     donation_receipt_master drm
     ON drm.receipt_id = dri.receipt_id JOIN
     account_management_master amm
     ON amm.account_id = dri.account_id JOIN
     user_master um
     ON um.user_master_id = drm.user_master_id JOIN
     user_address_info uai
     ON uai.user_master_id = um.user_master_id JOIN
     city_master cm
     ON cm.city_id = uai.city_id
WHERE dri.temple_id = '1'
GROUP BY dri.receipt_id, dri.account_id;

下一步。所有表都有明显的索引吗?也就是说,每个表似乎都有一个id,这些应该被声明为键(最好是主键)。例如,city_master(city_id)

接下来,donation_receipt_info(temple_id, receipt_id, account_id)上应该有一个索引。这应该有助于where。注意:如果temple_id实际上是一个整数,where子句应表示为WHERE dri.temple_id = 1 - 没有引号。你不希望MySQL混淆并决定不使用索引。

这些变化可能会有所帮助。这样的查询似乎需要5-6分钟。