Mysql查询每天最高投票

时间:2013-01-16 12:13:44

标签: php mysql sql

我有一个以下的数据库表review_vote

review_id | user_id | status | date_added 
 2             3        good     20130116135259
 3             3        normal   20130116145259
 4             2        normal   20130116155259
 5             2        good     20130116165259
 6             2        good     20130116175259
 7             1        great    20130116185259
 8             3        good     20130117135259
 9             3        normal   20130117145259

目前我可以使用以下查询获得最高票数:

SELECT review_id FROM review_vote GROUP BY review_id HAVING COUNT(*) = 
(
   SELECT MAX(x.counts) FROM 
   ( 
       SELECT review_id, COUNT(*) counts FROM review_vote GROUP BY review_id
   )x 
) 
order by date_added desc

但如果我需要每天获得最高票数,我该如何修改上面的代码?这意味着如果今天2013-01-16我需要获得昨天的最高票数2013-01-15

我尝试使用date_added = CURDATE()失败了。 SQLFIDDLE:http://sqlfiddle.com/#!2/9a2b5/6

更新查询:

CREATE TABLE IF NOT EXISTS `review_vote` (
  `review_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `status` varchar(100) NOT NULL,
  `date_added` varchar(100) NOT NULL,
  KEY `review_id` (`review_id`,`user_id`) USING BTREE
) ENGINE=MyISAM DEFAULT CHARSET=utf8;



INSERT INTO `review_vote` (`review_id`, `user_id`, `status`, `date_added`) VALUES
(223, 2, 'lame', '20130116195259');
INSERT INTO `review_vote` (`review_id`, `user_id`, `status`, `date_added`) VALUES(222, 2, 'lame', '20130115195259');

3 个答案:

答案 0 :(得分:1)

只需在您所处的条件中添加:

DATE_FORMAT(date_added, '%Y-%m-%d') = CURDATE()

根据您的错误进行更新

SELECT review_id FROM review_vote AS RV WHERE DATE_FORMAT(RV.date_added, '%Y-%m-%d') = CURDATE()    
    GROUP BY review_id HAVING COUNT() = 
(
    SELECT MAX(x.counts) FROM 
    (
        SELECT review_id, COUNT() counts FROM review_vote GROUP BY review_id
    )x
)

请查看演示:demo

答案 1 :(得分:0)

SELECT   review_id
FROM     review_vote
WHERE    date_added LIKE '20130115%'
GROUP BY review_id
ORDER BY COUNT(*) DESC
LIMIT    1

但实际上您应该考虑将date_added列更改为适当的时间类型,例如DATETIME or TIMESTAMP

答案 2 :(得分:0)

将以下内容添加到WHERE子句中:

`date_added` BETWEEN
  DATE_FORMAT(DATE_SUB(CURDATE(), INTERVAL 1 DAY), '%Y%m%d')
  AND DATE_FORMAT(CURDATE(), '%Y%m%d')

确保您在date_added上有索引!

日期函数的文档全部在此处:http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

如果您的date_added列是原生日期类型,生活会更容易。