加快SQL查询以获取月度数据

时间:2018-02-24 11:54:52

标签: mysql

我正在获取每月统计数据的分析,我的查询似乎很慢我对mysql不太好,我不确定什么是最好的方法,也许这是正确的。在StackOverflow上搜索后,我发现了我认为这是获取数据的最佳方式。

我需要在一个月内得到每天的统计数/统计数,我有一个月的日期,就像这样。

enter image description here

我正在对我的统计数据表运行查询。

SELECT day, (SELECT COUNT(*) FROM stats WHERE DAYOFMONTH( stats.timestamp ) = DW.day_id AND MONTH( stats.timestamp ) = MONTH(CURDATE()) AND YEAR( stats.timestamp ) = YEAR(CURDATE()) AND stats.user_id = 1) AS taly FROM daysoffthemonth DW

这是我查询的输出。

enter image description here

这有效,但如上所述它开始变得非常慢,特别是现在我的统计表开始填充大量数据。

会不会对最佳做法提出任何建议?

由于

评论中建议的查询结果。

enter image description here

1 个答案:

答案 0 :(得分:1)

你应该避免子查询列结果..
而不是子查询尝试使用连接

SELECT c.*
FROM conversations c
LEFT JOIN users_x_conversations uxc1 
   ON uxc1.user_id = 1 AND c.conversation_id = uxc1.conversation_id
LEFT JOIN users_x_conversations uxc2 
   ON uxc1.user_id = 2 AND c.conversation_id = uxc2.conversation_id
LEFT JOIN users_x_conversations uxc3 
   ON uxc1.user_id = 3 AND c.conversation_id = uxc3.conversation_id
WHERE uxc1.user_id is not null and ucx2.user_id is not null and ucx3.id is not null
Group by c.id

或避免1

 SELECT DW.day, ifnull(COUNT(*),0) taly
 FROM daysoffthemonth DW 
 LEFT  JOIN stats ON DAYOFMONTH( stats.timestamp ) = DW.day_id 
    AND  AND MONTH( stats.timestamp ) = MONTH(CURDATE()) 
      AND AND YEAR( stats.timestamp ) = YEAR(CURDATE()) 
        AND stats.user_id = 1
 GROUP BY DW.day