替换此mysql查询

时间:2018-04-14 17:16:14

标签: mysql sql

我有两个表cinfo和astd。下面的查询需要花费很多时间来返回结果。请告诉备用查询。

           SELECT cinfo.state, SUM(cstd.total_total_persons) as total, SUM(cstd.total_total_females) as girl  FROM cinfo 
           JOIN cstd WHERE cinfo.id = cstd.College_id
           GROUP BY cinfo.state

2 个答案:

答案 0 :(得分:0)

首先,在JOIN中使用ON子句而不是where。

关于性能,请检查两个表上的索引。另外,请查看EXPLAIN为您的查询显示的内容。

SELECT 
    cinfo.state, 
    SUM(cstd.total_total_persons) as total, 
    SUM(cstd.total_total_females) as girl
FROM cinfo 
JOIN cstd 
ON cinfo.id = cstd.College_id
GROUP BY cinfo.state

答案 1 :(得分:0)

对于此查询:

SELECT cinfo.state, SUM(cstd.total_total_persons) as total, 
       SUM(cstd.total_total_females) as girl
FROM cinfo JOIN
     cstd
     ON cinfo.id = cstd.College_id
GROUP BY cinfo.state;

您可以在cstd(College_id, total_total_persons, total_total_females)上添加索引。您无法更好地优化查询。