2014-02-22 286 views
0

我有一個問題... 我在這個網站搜索任何解決方案...我嘗試了他們,但在一個鍛鍊:( 所以我想獲得前10名的結果4天前通過的意見...... 所以我嘗試代碼那樣:MySQL前10天7天前

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)向數據庫提交日期是否可以解決這個問題?如果你想顯示的日期和時間

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; 

這:

+1

您提交的日期到MySQL用'時間()在_PHP_或MySQL自身的'函數['TIME()'函數(HTTP ://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_time)? 「日期」列的數據類型是什麼?如果你使用PHP'time()'填充它,它可能是一個unix時間戳 –

+0

「沒有什麼作用」是什麼意思?你能顯示一些樣本數據嗎? –

+0

日期的數據類型是什麼? –

回答

1

試試這個。

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