使用多个选择作为列优化查询

Posted

技术标签:

【中文标题】使用多个选择作为列优化查询【英文标题】:Optimising query with multiple selects as columns 【发布时间】:2020-10-30 05:40:32 【问题描述】:

我有一个查询:

 SELECT DISTINCT player_1 AS player, 
                (SELECT COUNT(*) FROM results WHERE player_1=player OR player_2=player) AS since_start_matches, 
                (SELECT COUNT(*) FROM results WHERE (player_1=player OR player_2=player) AND ht_total_goals=0) AS since_start_ht_0,
                (SELECT COUNT(*) FROM results WHERE (player_1=player OR player_2=player) AND ht_total_goals=1) AS since_start_ht_1,
                (SELECT COUNT(*) FROM results WHERE (player_1=player OR player_2=player) AND ht_total_goals=2) AS since_start_ht_2,
                (SELECT COUNT(*) FROM results WHERE (player_1=player OR player_2=player) AND ht_total_goals=3) AS since_start_ht_3,
                (SELECT COUNT(*) FROM results WHERE (player_1=player OR player_2=player) AND ht_total_goals=4) AS since_start_ht_4,
                (SELECT COUNT(*) FROM results WHERE (player_1=player OR player_2=player) AND ht_total_goals>=5) AS since_start_ht_5_plus
FROM results ORDER BY player

results 表有 25000 个条目,执行此查询大约需要 7 秒,这太长了。该查询效率极低,因为我创建的每一列都在同一个表上再次搜索,但条件不同。

我尝试在 where 子句中索引感兴趣的列。这会关闭几秒钟。但是还是太慢了。

处理此类查询的最佳方法是什么?

我正在使用 MariaDB 10.2

【问题讨论】:

也就是说,最好的方法可能是处理应用程序代码中数据显示的所有问题 【参考方案1】:

取消透视数据然后聚合:

 SELECT player, 
        COUNT(*) AS since_start_matches, 
        SUM(ht_total_goals=0) AS since_start_ht_0,
        SUM(ht_total_goals=1) AS since_start_ht_1,
        SUM(ht_total_goals=2) AS since_start_ht_2,
        SUM(ht_total_goals=3) AS since_start_ht_3,
        SUM(ht_total_goals=4) AS since_start_ht_4,
        SUM( ht_total_goals>=5) AS since_start_ht_5_plus
FROM ((SELECT player_1 as player, ht_total_goals
       FROM results
      ) UNION ALL
      (SELECT player_2 as player, ht_total_goals
       FROM results
      )
     ) p
GROUP BY player

【讨论】:

【参考方案2】:

您可以使用LEFT JOINconditional aggregation,如下所示:

SELECT  player_1 AS player, 
                COUNT(T2.player_1) AS since_start_matches, 
                SUM(CASE WHEN T2.ht_total_goals=0 THEN 1 END) AS since_start_ht_0,
                SUM(CASE WHEN T2.ht_total_goals=1 THEN 1 END) AS since_start_ht_1,
                SUM(CASE WHEN T2.ht_total_goals=2 THEN 1 END) AS since_start_ht_2,
                SUM(CASE WHEN T2.ht_total_goals=3 THEN 1 END) AS since_start_ht_3,
                SUM(CASE WHEN T2.ht_total_goals=4 THEN 1 END) AS since_start_ht_4,
                SUM(CASE WHEN T2.ht_total_goals>=5 THEN 1 END) AS since_start_ht_5_PLUS
FROM results T1 LEFT JOIN results T2 
ON (T2.player_1=T.player OR T2.player_2=T.player)
GROUP BY T1.PLA

YER_1 按玩家订购

【讨论】:

以上是关于使用多个选择作为列优化查询的主要内容,如果未能解决你的问题,请参考以下文章

SQL Server查询优化和事务处理

优化 Mysql 查询

使用多个联合优化查询性能

使用多个 OUTER APPLY 优化查询

oracle查询优化

使用 from 子句优化的 SQL 更新查询