문제

I have a problem... I search in this site for any solutions... I tried them but on one workout :( So I'm trying to get the top 10 results for 7 days ago by views... So I try codes like that:

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

or

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

or

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

or

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

I try them with any combination with NOW() TIME() DATE() CURDATE() SUBDATE() SUBTIME() DATE_SUB() etc... but nothing works :( I really don't know what is the problem. I submit the date to database with time() function(PHP) can it be that the problem?

도움이 되었습니까?

해결책

Try this:

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;

And this if you want the date and time displayed.

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

Sample data:

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top