Forum Moderators: coopster
SELECT * FROM tablename ORDER BY RND() LIMIT 1;
Do you have other solutions?
Thanks very much!
let say these are your order IDs (or dates or whatever):
001,002,003,004,005,006,007,008
And you want to randomly pick an item with an id>=005 simply:
SELECT * FROM tablename where id>=005 ORDER BY RAND() LIMIT 1;
if you want you can show one of the queries you want to select a random element from. I'm sure there is a simple SQL way to do it (there is for almost anything.)
SN
I suppose there isn't a way to random pick one of the 4 product rows with the largest IDs, right?
Here's the query.
$newprod_result = mysql_query("select interface, onelinesummary, picture, productname, DATE_FORMAT(release, '%M %Y') AS verbaldate, categories.subcat, categories.maincat from hardware, categories WHERE interface!= 'Bluetooth' AND status = 1 AND subcategory = $subcat AND categories.id = $subcat order by hardware.id desc limit 4");
here is somethign that works sort of:
SELECT
interface
,onelinesummary
,picture
,productname
,DATE_FORMAT(release,'%M %Y')AS verbaldate
,categories.subcat
,categories.maincat
FROM hardware,categories
WHERE interface!='Bluetooth'
AND status=1
AND subcategory=$subcat
AND categories.id=$subcat
ORDER BY ROUND((10000000000-hardware.id)/4)*4+ROUND(RAND(4)*3)hardware.id
LIMIT 1;
This will retrieve one random line from the the last four records ONLY if all ID'S are exactly one appart.
Alternatively you could select into a temporary table and hten retrieve one row. But since the data is little, I'd jstu select one on the client end in php.
SN
"This will retrieve one random line from the the last four records ONLY if all ID'S are exactly one appart."
Unfortunately, the IDs aren't exactly consecutive.
How do I go about the alternate solution?
Actually, I was thinking of something more 'conventional'. Rather than trying to complicate matters inside one single query, I can do the same select query and then random pick a row first.
Do you know how to do that? (Pick a random row from a fetch query, I mean)
$randrow = rand(1,5);
echo $yourarray[$randrow];
you could also use it more dynamically in the case that you are not always getting 5 rows.
$max = count($yourarray);
$randrow = rand(1,$max);
echo $yourarray[$randrow];