MySQL在group by和count上查询速度非常慢

时间:2017-09-26 05:22:00

标签: mysql sql

我有一个包含以下表格的数据库:

医院(~28K行), 检查(~116K行), 问题(~290K行)

医院进行检查,每次检查都有零个或多个问题。我有以下查询:

SELECT count(*) as count, BName, BCity, BAddress, BState, BZip, Ins_date, BCountry, Ins_Type
FROM ( SELECT b.id as ID, b.hospital_name as BName, b.city as BCity, b.address as BAddress, b.country as BCountry, b.state as BState, b.zip as 
BPostal, i.date as Ins_date, v.type as Ins_Type
FROM hospital_table b, inspection_table i, issue_table v
WHERE b.id = i.business_id
    AND i.id = v.inspection_id
    ORDER BY b.hospital_name, i.date DESC ) AS sumissues
GROUP BY ID
ORDER BY count DESC;

我期望得到的输出是:

112 | Burnaby Memorial | Burnaby | 3935 Kincaid St | BC | 2017-07-19 | Canada | Cleanliness

问题是运行大约需要40秒。我有一个外键索引和inspection_table.date。关于如何优化这个的任何想法?

1 个答案:

答案 0 :(得分:0)

查看您的代码

不需要subselect的顺序,也不需要subselect

SELECT 
     count(*) as count
    , b.hospital_name as BName
    , b.city as BCity
    , b.address as BAddress
    , b.country as BCountry
    , b.state as BState
    , b.zip as BPostal
    , i.date as Ins_date
    , v.type as Ins_Type
FROM hospital_table b
INNER JOIN inspection_table i ON b.id = i.business_id
INNER JOIN  issue_table v ON i.id = v.inspection_id
GROUP BY b.id 
ORDER BY count DESC, b.hospital_name, i.date

但要注意@User_by_Already

中的内容

为此以及为其他列避免更多行组,如果您不关心这些列的结果,则可以使用(假)聚合函数

SELECT 
     count(*) as count
    , b.hospital_name as BName
    , b.city as BCity
    , b.address as BAddress
    , b.country as BCountry
    , b.state as BState
    , b.zip as BPostal
    , min(i.date) as Ins_date
    , min(v.type) as Ins_Type
FROM hospital_table b
INNER JOIN inspection_table i ON b.id = i.business_id
INNER JOIN  issue_table v ON i.id = v.inspection_id
GROUP BY b.id
ORDER BY count DESC, b.hospital_name, i.date