在MySQL中生成年/月的列表

时间:2010-11-12 06:38:50

标签: mysql date

目前,在我的博客中,我使用以下代码获取了年份/日期列表:

    $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) {
                $nav[$year][$id] = $temp['count'];
            }
        }
    }

    krsort($nav);

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

一开始这一切都很棒,但现在我已经有了几年的数据和几个月的时间,这不会再削减了。我之前从未做过这样的事情,我通常会处理时间戳。

1 个答案:

答案 0 :(得分:1)

您可以使用此一个查询替换循环

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)