加速SQL嵌套查询

时间:2016-09-13 09:03:36

标签: mysql sql

我有一个名为ntr_perf的表,其中包含以下列:datacosnetworktot_regtot_rej。 我需要为每对data-cos得到tot_regtot_rej的总和(我需要获取所有数据 - cos对,并使用相同的数据为所有网络建立值的总和 - cos对)。

我使用以下MySQL查询:

SELECT DISTINCT 
    data AS d, 
    cos AS c, 
    (SELECT SUM(tot_reg) FROM ntr_perf WHERE data=d AND cos=c) AS sumattempts, 
    (SELECT SUM(tot_rej) FROM ntr_perf WHERE data=d AND cos=c) AS sumrej FROM ntr_perf

即使表只有91.450行(表中有多列索引数据 - cos),也需要很长时间。

是否可以加快查询速度?

4 个答案:

答案 0 :(得分:1)

这正是group by的设计目标。

试试这个:

SELECT data,cos,SUM(tot_reg),SUM(tot_rej) from ntr_perf group by data,cos

答案 1 :(得分:0)


您可以使用此查询

SELECT data AS d, cos AS c,
SUM(tot_reg), SUM(tot_reg) where 
data='d' AND cos='c' group by data , cos ;

希望你有。另外请告诉我,会帮助你

答案 2 :(得分:0)

试试这个,一个小组

SELECT data d,
       cos c,
       SUM(tot_reg) sumattempts,
       SUM(tot_rej) sumrej
FROM ntr_perf 
WHERE data = 'd'  -- if these are values, put in single quotes
AND cos = 'c' -- if these are values, put in single quotes
GROUP BY data, -- even though aliased, the original name needs to be used on the GROUP BY
         cos -- even though aliased, the original name needs to be used on the GROUP BY

答案 3 :(得分:0)

这会将您的查询分组并过滤您的总和,因为您发布了WHERE条件:

SELECT 
    data AS d, 
    cos AS c,
    SUM(IIF(data='d' AND cos='c', tot_reg, 0) AS sumattempts,
    SUM(IIF(data='d' AND cos='c', tot_rej, 0)) AS sumrej 
FROM 
    ntr_perf 
GROUP BY 
    data,
    cos
相关问题