tags:

views:

188

answers:

2

I'm currently displaying a random row from all the entries and that works fine.

SELECT * FROM $db_table where live = 1 order by rand() limit 1

now, i'd like to limit it to the last 100 entries in the db.

every row in the db has an ID and a timestamp.

it's a small database, so overhead-minimization is not a priority.

thanks!

EDIT:

Still can't get it running.. I get a mysql_fetch_array error:

"Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource

Here's all of my code:

<?php $sql = "SELECT * FROM
(SELECT * FROM $db_table ORDER BY $datetime DESC LIMIT 100)
ORDER BY rand() LIMIT 1";
$query = mysql_query($sql);
while($row = mysql_fetch_array($query)) {

echo "".$row['familyname']."";

} ?>

Thanks again!

+4  A: 

This is what I came up with off the top of my head. I've tested it and it works in SQLite, so you shouldn't have much trouble with MySQL. The only change was that SQLite's random function is random() not rand():

SELECT * FROM
  (SELECT * FROM $db_table ORDER BY $timestamp DESC LIMIT 100)
ORDER BY rand() LIMIT 1
Kyle Cronin
What exactly does ORDER by rand() do? There seem to be a lot of complaints on mysql.com's forums about performance problems using this method of randomization, though those might be from poorly designed queries or databases.
Calvin
Thanks! Unfortunately I can't get it to run.. Updated the original question. Thanks again!
dot
You need to replace $db_table with your table name. I don't know what you can replace $timestamp with. I used the MySQL command, NOW(). Also, you need to assign an alias to the outer select by putting something like "AS r1" after "DESC LIMIT 100)"
Calvin
Thanks, the alias did the trick!
dot
+1  A: 
Calvin