Web Hosting Talk







View Full Version : MySQL [limit rand]


raulgonzalez
11-19-2007, 05:14 PM
Hello,

I wanted to do the following:

Select the last 7 records from MySQL and out of those 7 records only disply 1 ramdomly.

I tried:
SELECT * FROM pdf ORDER BY RAND() DESC limit 7
But it returns 7 records

I tried:
SELECT * FROM pdf ORDER BY RAND() DESC limit 1
But it returns 1 record from the whole database instead of the last 7 entires.

Any idea how I can accomplish that. I haven't searched, I thought I should ask first before jumping into a research.

Any ideas?

Thanks.

Steve_Arm
11-19-2007, 05:16 PM
Do it with code. Select the 7 last and choose randomly one from the array with php. By the way why are you ranting, those queries are doing the correct selection :)

sscon
11-19-2007, 08:07 PM
You're not ordering by whatever field makes those records the "last" (id field, etc.)

I'm sure there's a better way, but using something with subselects like this should work -

select * from (select * from pdf order by [id] desc limit 0,7) as [whatever] order by rand() limit 0,1

(Replace [id] with whatever column makes those records the "last" records (timestamp, auto increment id, etc.) and [whatever] with whatever you want, it doesn't matter.)

raulgonzalez
11-25-2007, 01:30 PM
Sorry for not getting back to you soon, you know, the hollydays,

SSCON, your SQL query suggestion worked like a cham. I knew there would be a way to do the job right at the MYSQL query.

This is what I used:
$query = "select * from (select * from pdf order by pid desc limit 0,7) as pid order by rand() limit 0,1";

Thanks again.