MySQL Top10 7天前

时间:2014-02-22 18:20:47

标签: mysql days

我有问题...... 我在这个网站搜索任何解决方案......我试过但是在一次锻炼:( 所以我试图通过观点获得7天前的前10名结果...... 所以我尝试这样的代码:

SELECT * FROM `data` 
WHERE cast(`date` as DATE) BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) 
AND CURDATE() ORDER by `viewed` DESC LIMIT 0,10

SELECT * FROM `data` 
WHERE `date` > (NOW() - INTERVAL 7 DAY) 
ORDER by `viewed` DESC LIMIT 0,10

SELECT * FROM `data` 
WHERE DATE(`date`) = DATE_SUB(NOW(), INTERVAL 7) 
ORDER by `viewed` DESC LIMIT 0,10

SELECT * FROM `data` 
WHERE `date` >= SUBDATE(NOW(), INTERVAL 7 DAY) 
ORDER by `viewed` DESC LIMIT 0,10

我可以与NOW() TIME() DATE() CURDATE() SUBDATE() SUBTIME() DATE_SUB()等任意组合进行尝试...但是什么都行不通:(我真的不知道是什么问题。我用time()函数(PHP)将日期提交到数据库可以是问题吗?

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT date, viewed FROM data
WHERE date BETWEEN UNIX_TIMESTAMP(NOW() - INTERVAL 7 day) AND UNIX_TIMESTAMP(NOW())
ORDER BY viewed DESC
LIMIT 0,10;

如果您想要显示日期和时间,请执行此操作。

SELECT FROM_UNIXTIME(date), viewed FROM data
WHERE date BETWEEN UNIX_TIMESTAMP(NOW() - INTERVAL 7 day) AND UNIX_TIMESTAMP(NOW())
ORDER BY viewed DESC
LIMIT 0,10

示例数据:

CREATE TABLE data 
    (
     id int auto_increment primary key, 
     date varchar(10),
     viewed int
    );

INSERT INTO data
(date, viewed)
VALUES
(1392749561, 50),
(1392749950, 25),
(1392850985, 10),
(1393023471, 75),
(1392936840, 100);

SQLFiddle demo