SQL查询太慢 - 寻找替代方法来编写它

时间:2017-03-27 15:04:35

标签: mysql performance

我有这个mysql查询可以满足它的需要,但是加载内容需要很长时间,因为我的其他查询运行得非常好而且快速。有没有更好的方法呢?我只是希望它加载更快。这是我的疑问:

SELECT 
    DISTINCT( # Without this I get too many results
        CONCAT_WS(' ', 
            MONTHNAME(a.DateTimeViewed), 
            YEAR(a.DateTimeViewed)
        )
    ) AS ViewedDate, # Displays as "January 2017" (example)
    (
        SELECT COUNT(b.ViewID) 
        FROM views b 
        WHERE 
            MONTH(b.DateTimeViewed) = MONTH(a.DateTimeViewed) AND 
            YEAR(b.DateTimeViewed) = YEAR(a.DateTimeViewed)
    ) as TotalViews 
FROM views a 
    WHERE a.DateTimeViewed >= date_sub(now(), interval 6 month) 
    ORDER BY YEAR(a.DateTimeViewed) ASC, MONTH(a.DateTimeViewed) ASC

1 个答案:

答案 0 :(得分:0)

你工作太辛苦了。

SELECT  CONCAT_WS(' ', MONTHNAME(a.DateTimeViewed), YEAR(a.DateTimeViewed)
                 ) AS ViewedDate,
        COUNT(*) as TotalViews
    FROM  views a
    WHERE  a.DateTimeViewed >= date_sub(now(), interval 6 month)
    ORDER BY  YEAR(a.DateTimeViewed) ASC, MONTH(a.DateTimeViewed) ASC

由于您从此刻开始提前6个月备份,因此您只能获得第一个月的部分时间。也许你想换一行:

WHERE a.DateTimeViewed >= CONCAT(LEFT(CURDATE() - INTERVAL 6 MONTH, 7), '-01')

COUNT(*)是计算行数的常用方法。 COUNT(x)也会这样做,但会增加使用x IS NULL过滤掉行的工作。