0

我有一个以下数据库表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');
4

3 回答 3

1

只需将其添加到您的 where 条件中:

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
)

请看演示:演示

于 2013-01-16T12:18:01.047 回答
0
SELECT   review_id
FROM     review_vote
WHERE    date_added LIKE '20130115%'
GROUP BY review_id
ORDER BY COUNT(*) DESC
LIMIT    1

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

于 2013-01-16T12:16:18.680 回答
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如果您的列是原生日期类型,那么您的生活会更轻松。

于 2013-01-16T12:22:49.183 回答