[英]Optimising query with multiple selects as columns
I have a query I made:我有一个查询:
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
The results
table has 25000 entries and it takes around 7 seconds to do this query, which is far too long. results
表有 25000 个条目,执行此查询大约需要 7 秒,这太长了。 The query is incredibly inefficient as each column I'm creating is searching again on the same table but with different conditions.该查询非常低效,因为我正在创建的每一列都在同一个表上再次搜索但条件不同。
I tried indexing the columns of interest in my where clause.我尝试在 where 子句中索引感兴趣的列。 This knocks off a couple of seconds.
这会关闭几秒钟。 But it's still too slow.
但是还是太慢了。
What is the best approach to handle this kind of query?处理此类查询的最佳方法是什么?
I'm using MariaDB 10.2我正在使用 MariaDB 10.2
Unpivot the data then aggregation: Unpivot 数据然后聚合:
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
You can use the LEFT JOIN
and conditional aggregation
as follows:您可以使用
LEFT JOIN
和conditional 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 ORDER BY player YER_1 玩家订购
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.