我想查找按月分组的每个用户的帖子数。 我目前正在使用INT(10)无符号来存储帖子的日期。
这会是一个超级快速的方法吗?
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的记录表现良好。欢呼声。
答案 0 :(得分: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