tags:

views:

1183

answers:

2

What's the best way to express this in one SQL query?

"Select a few random items that fall within x days of the newest item in the table."

I tried the following:

SELECT *
FROM table
HAVING `timestamp` >= SUBDATE(MAX(`timestamp`), INTERVAL 5 DAY)
ORDER BY RAND()
LIMIT 10

But this only gives me a single result, not 10. WHERE instead of HAVING doesn't cut it because of the use of MAX().

+3  A: 

You probably want your MAX statement in a sub-query:

SELECT *
FROM table
WHERE `timestamp` >= SUBDATE((SELECT MAX(`timestamp`) FROM table), INTERVAL 5 DAY)
ORDER BY RAND()
LIMIT 10
Blixt
D'oh, so obvious. I hoped for something without the need for a subquery for my DAO, but with a bit of trickery it works fine.Thanks.
deceze
A: 
SELECT *
FROM table
where `timestamp` >= (select SUBDATE(MAX(`timestamp`), INTERVAL 5 DAY) from table )
ORDER BY RAND()
LIMIT 10;
ZA