【问题标题】:How to optimize a query that is a join of 2 very similar queries but with different aggregation如何优化作为 2 个非常相似但聚合不同的查询的连接的查询
【发布时间】:2021-11-09 16:05:06
【问题描述】:

我有以下疑问:

SELECT OBJ_DESC_ERRORS.description, OBJ_DESC_ERRORS.object, OBJ_DESC_ERRORS.count_errors, OBJ_ERRORS.count_total FROM 

(SELECT `metrics_event`.`description`, `metrics_event`.`object`, COUNT(`metrics_event`.`id`) AS `count_errors` FROM `metrics_event` 
INNER JOIN `metrics_session` ON (`metrics_event`.`session_id` = `metrics_session`.`id`) 

WHERE (`metrics_session`.`training_id` = 4 AND NOT (`metrics_session`.`completed_at` IS NULL) ) 
GROUP BY `metrics_event`.`description`, `metrics_event`.`object` ORDER BY `count_errors` DESC ) as OBJ_DESC_ERRORS

JOIN

(SELECT  `metrics_event`.`object`, COUNT(`metrics_event`.`id`) AS `count_total` FROM `metrics_event` 
INNER JOIN `metrics_session` ON (`metrics_event`.`session_id` = `metrics_session`.`id`) 

WHERE (`metrics_session`.`training_id` = 4 AND NOT (`metrics_session`.`completed_at` IS NULL) ) 
GROUP BY `metrics_event`.`object` ORDER BY `count_total` DESC ) as OBJ_ERRORS

ON OBJ_DESC_ERRORS.object = OBJ_ERRORS.object

产生以下结果:

如您所见,我基本上运行了两次相同的查询。原因是我需要将 count_errors 分解为对象 + 描述的每个聚合,但我还需要 count_total 仅按对象聚合。这是我能想到的方式。现在我想知道这是否是我能做的最好的,或者是否可以进一步优化。

如果是这样,我不知道怎么做。谷歌搜索和搜索类似的主题很困难,因为优化任务取决于查询本身,所以这里的关键字对我没有多大帮助。

【问题讨论】:

    标签: mysql sql query-optimization


    【解决方案1】:

    摆脱内心的ORDER BYs;他们没有做任何有用的事情。

    像这样重写查询:

    SELECT 
        me.description,
        me.object,
        SUM(...) AS count_errors,
        SUM(...) AS count_total
    FROM  `metrics_event` AS me
    INNER JOIN  `metrics_session` AS ms  ON (me.`session_id` = ms.`id`)
    WHERE ms.`training_id` = 4
          ms.`completed_at` IS NOT NULL
    GROUP BY  me.`description`, me.`object`
    ORDER BY  `count_total` DESC
    

    由于布尔表达式的计算结果为 1 为 TRUE,否则为 0,请将 SUM() 的参数设计为提供所需 COUNT 的布尔表达式。

    【讨论】:

    • 第二个 SUM (count_total) 在这里很棘手,因为它需要是 count_errors 的总和,但按对象分组。所以这里是带有条件的查询:SELECT me.description, me.object, SUM( me.error_severity > 0) AS count_errors, SUM(me.error_severity > -1) AS count_total FROM metrics_event AS me INNER JOIN metrics_session AS ms ON (me.session_id = ms.id) WHERE ms。 training_id = 4 AND ms.completed_at 不为空 GROUP BY me.description, me.object ORDER BY count_total DESC。但我不确定如何将该条件案例添加到 count_total
    猜你喜欢
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    • 2021-12-13
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多