tags:

views:

155

answers:

2

Hi all,

I'm running the following code to get a random entry from a dictionary:

SELECT * FROM tbl_dict WHERE 1 ORDER BY RAND() LIMIT 1

This works great, but as soon as I expand there WHERE clause the query fails. What I need is something like...

SELECT * FROM tbl_dict WHERE 1 and lock='0' ORDER BY RAND() LIMIT 1

Can anyone point out to me where I'm going wrong? My mind has turned to peanut butter.

Thank you!

A: 

Never mind, this is wrong for what you're trying to do.

You do have a synthetic auto_incremented id column on your table, right?

if so, then why not:

  select * from tbl_dict where id 
   = (select floor( rand() * ( max(b.id) + 1) ) from tabl_dict b );
tpdi
Thanks! I'll keep this code aside for the production version.
Aaron
+5  A: 

lock is a reserved word for MySQL. You have to put it in backticks (`) or double-quotes (in ansi mode) if you want to use it as an identifier.

You might also be interested in http://jan.kneschke.de/projects/mysql/order-by-rand.
ORDER BY Rand() might or might not be a bit too suboptimal in your case when it comes to speed.

VolkerK
Thank you! I was in such a rush prototyping this had completely slipped my mind, thanks again.
Aaron