0

我想找到按月分组的每个用户的帖子数。我目前正在使用 INT(10) unsigned 来存储帖子的日期。

什么是一个超级快速的方法来做到这一点?

CREATE TABLE IF NOT EXISTS `media` (
  `pid` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `class` tinyint(1) NOT NULL DEFAULT '1',
  `date_class_changed` int(10) unsigned NOT NULL,
  `title` char(5) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL,
  `url` varchar(1024) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `media` enum('image','video') CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `thumb` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `description` varchar(140) COLLATE utf8_unicode_ci NOT NULL,
  `username` varchar(16) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `date` int(10) unsigned NOT NULL,
  `file` varchar(1024) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `hash` char(32) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `hashtag` text CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `meta` varchar(255) CHARACTER SET latin1 COLLATE latin1_general_ci NOT NULL,
  `ip` int(10) unsigned NOT NULL,
  `kind` tinyint(1) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`pid`),
  UNIQUE KEY `title` (`title`),
  KEY `hash` (`hash`),
  KEY `class_date` (`class`,`date_class_changed`),
  KEY `username` (`username`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1022724 ;

这是表格,我在说,我想显示每个用户每个 mont 的帖子数,例如:2012 年 9 月,用户 X,N 个帖子等。

在@fthiella 的帮助下,我使用的查询是:

SELECT
    DATE_FORMAT(FROM_UNIXTIME(`date`), '%Y-%m') as YearMonth, username, COUNT(*) as Posts
FROM
  media
WHERE username = 'foobar'
GROUP BY 1
ORDER BY 1 DESC

感谢上帝,它足够快,现在我会尝试优化以防它不使用索引,但现在几乎 1M 的记录做得很好。干杯。

4

1 回答 1

1
SELECT
    DATE_FORMAT(FROM_UNIXTIME(`date`), '%Y-%m') as YearMonth,
    username,
    COUNT(*) as Posts
FROM
  media
GROUP BY
    DATE_FORMAT(FROM_UNIXTIME(`date`), '%Y-%m') as YearMonth,
    username
于 2013-02-05T12:23:16.107 回答