此mysql查询的替代方法

dffbzjpn  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(273)

我有两张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
b1zrtrql

b1zrtrql1#

首先,在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
ru9i0ody

ru9i0ody2#

对于此查询:

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) . 要优化查询,您所能做的已经不多了。

相关问题