2017-10-13 61 views
0

我从我的EXPLAIN查询中获得以下内容。我不知道如何使用它来改善我的查询性能。我的查询如下:想不通为什么MYSQL查询是如此之慢

SELECT 
    `b`.`business_name` AS `Name`, 
    `b`.`address` AS `Address`, 
    `b`.`city` AS `City`, 
    `b`.`phone_number` AS `Phone`, 
    `b`.`state` AS `Prov`, 
    `i`.`date` AS `Last_Observed`, 
    group_concat(`v`.`notes` separator ', ') AS `Notes`, 
    `v`.`critical` AS `Criticality`, 
    `i`.`type` AS `Inspection_Type`, 
    `i`.`rating` AS `Rating` 
FROM (`fs_v1_violation_table` `v` 
LEFT JOIN (`fs_v1_inspection_table` `i` 
LEFT JOIN `fs_v1_business_table` `b` ON((`b`.`id` = `i`.`business_id`))) 
ON((`i`.`id` = `v`.`inspection_id`))) 
WHERE `v`.`type` = 'Cleanliness' AND (
    b.city = 'North Vancouver' 
    OR b.city = 'Vancouver' 
    OR b.city = 'White Rock' 
    OR b.city = 'West Vancouver' 
    OR b.city = 'Burnaby' 
    OR b.city = 'Langley' 
    OR b.city = 'Maple Ridge' 
    OR b.city = 'Delta' 
    OR b.city = 'Surrey') 
GROUP BY `i`.`id` 
ORDER BY `i`.`date` desc; 

任何想法,我可能会寻求提高性能?查询需要约3分钟。

Explain Query

+0

尝试EXPLAIN:https://dev.mysql.com/doc/refman/5.7/en/explain.html –

+0

使用'explain'方法检查。 – urfusion

+0

尝试在b.city上创建索引 –

回答

0

首先,您的查询似乎是对SQL标准,因为在选择列表中包含不在组中的列表中,也不是功能上依赖于列表中的组中的字段的字段,也不使用集合函数(如min()sum())进行汇总。不幸的是,MySQL允许这些查询在特定的sql模式设置下运行。幸运的是,这个设置现在默认关闭。

使用IN (...)代替一系列OR,并确保您在fs_v1_business_table表的id, city字段上具有多列索引以加快查询速度。您也可以考虑在fs_v1_inspection_table表的business_id, id, date字段中创建多列索引。

1

尽可能地减少行数量。

从'b.city'列创建索引。

示例SQL。

SELECT 
    `b`.`business_name` AS `Name`, 
    `b`.`address` AS `Address`, 
    `b`.`city` AS `City`, 
    `b`.`phone_number` AS `Phone`, 
    `b`.`state` AS `Prov`, 
    `i`.`date` AS `Last_Observed`, 
    group_concat(`v`.`notes` separator ', ') AS `Notes`, 
    `v`.`critical` AS `Criticality`, 
    `i`.`type` AS `Inspection_Type`, 
    `i`.`rating` AS `Rating` 
FROM `fs_v1_violation_table` AS `v` 
LEFT JOIN `fs_v1_inspection_table` AS `i` ON `i`.`id` = `v`.`inspection_id` 
LEFT JOIN `fs_v1_business_table` AS `b` ON `b`.`id` = `i`.`business_id` AND b.city IN ('North Vancouver', 'Vancouver', 'White Rock', 'West Vancouver', 'Burnaby', 'Langley', 'Maple Ridge', 'Delta', 'Surrey') 
WHERE `v`.`type` = 'Cleanliness' 
GROUP BY `i`.`id` 
ORDER BY `i`.`date` desc;