开发者

Generating a list of years/months in MySQL

Currently for my blog I get a list of years/dates using the following code:

    $monthList = array(
        1 => 'January',
        2 => 'February',
        3 => 'March',
        4 => 'April',
        5 => 'May',
        6 => 'June',
        7 => 'July',
        8 => 'August',
        9 => 'September',
        10 => 'November',
        11 => 'October',
        12 => 'December'
    );
    $nav = array();
    for ($year = 2009; $year <= date('Y'); $year++) {
        foreach ($monthList as $id => $month) {
            $this->tru->query->runRaw(array(
                'name' => 'get-headline-count',
                'sql' => 'SELECT
                        COUNT(id) as count
                    FROM 
                        wp_'.$this->getId().'_posts
                    WHERE
                        post_status = \'publish\' AND
                        post_type = \'post\' AND
                        post_parent = \'0\' AND
                        YEAR(post_date) = '.$year.' AND
                        MONTH(post_date) = '.$id.'',
                'connection' => 'article'
            ));
            $temp = $this->tru->query->getArray('get-headline-count');
            if ($temp['count'] > 0) {
                $na开发者_运维知识库v[$year][$id] = $temp['count'];
            }
        }
    }

    krsort($nav);

    return array(
        'month' => $monthList,
        'nav' => $nav
    );

This was all great at first, but now that I've got a few years worth of data and a few months this isn't going to cut it anymore. I've never done anything like this before, I usually deal with timestamps.


You can replace the loop with this one query

SELECT
   YEAR(post_date) as yr, MONTH(post_date) as mn, COUNT(id) as count
FROM 
    wp_posts
WHERE
    post_status = 'publish' AND
    post_type = 'post' AND
    post_parent = '0' 
GROUP BY YEAR(post_date), MONTH(post_date) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜