我提出了一个问题:
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
2条答案
按热度按时间91zkwejq1#
取消激活数据,然后进行聚合:
ctzwtxfj2#
你可以用
LEFT JOIN
以及conditional aggregation
具体如下:按玩家排序