我的表结构如下:
CREATE TABLE `scores` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`nick` VARCHAR(32) NOT NULL,
`count` SMALLINT(5) UNSIGNED ZEROFILL NOT NULL DEFAULT '00000',
`messages` SMALLINT(5) UNSIGNED ZEROFILL NOT NULL DEFAULT '00000',
`dated` DATE NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `nick_dated` (`nick`, `dated`),
INDEX `nick` (`nick`),
INDEX `count` (`count`),
INDEX `messages` (`messages`)
)
COMMENT='Chat scores'
COLLATE='utf8_general_ci'
ENGINE=MyISAM;
我希望编写一个查询,以便对于用户输入值nick
,我可以生成用户的:
- 总数
- 平均数
- 最近一天的计数
- 最高计数日期
我写的查询是:
SELECT s.`nick` AS `nick`,
s.`count` AS `recent`,
t.`total` AS `total`,
t.`avrg` AS `avrg`,
MAX(ss.`count`) AS `max`,
ss.dated
FROM (
SELECT `nick`,
SUM(`count`) AS `total`,
AVG(`count`) AS `avrg`,
MAX(`dated`) AS `dated` # For most recent activity
FROM `scores`
WHERE `nick` = 'hjpotter92'
) AS `t`
INNER JOIN scores s
ON s.nick = t.nick
AND s.dated = t.dated
INNER JOIN scores ss
ON ss.nick = t.nick
我可以选择前三个所需的值。但是我怎么能得到最高活动的日期。这是一个sqlfiddle。正如您在小提琴 DDL 中看到的,第 24 行
INSERT INTO `scores`
(`count`, `nick`, `dated`)
VALUES
(00052, 'hjpotter92', '2013-07-29');
计数最高的日期(MAX(ss.count)
正确获取为 52)是2013-07-29
,但我的选择查询返回 me July, 26 2013
。
我在哪里做错了?