View previous topic :: View next topic |
Author |
Message |
Primogenitor
Joined: 08 Jan 2005 Posts: 88
|
Posted: Wed Feb 02, 2005 11:18 Post subject: Randomly sort a query? |
|
|
Is there a way to randomize the order of rows in an SQL query result using SQL? I know I could load all the rows from the result back into the module, store them as locals, and then randomly pick one once I know how many there are. But it would be neater if I could have the SQL randomize the list and then I can just take the first result and ignore the rest. |
|
Back to top |
|
|
NoMercy
Joined: 03 Jan 2005 Posts: 123 Location: UK
|
Posted: Wed Feb 02, 2005 13:24 Post subject: |
|
|
Easy :)
Code: | SELECT * FROM table ORDER BY RAND() LIMIT 1 |
|
|
Back to top |
|
|
Primogenitor
Joined: 08 Jan 2005 Posts: 88
|
Posted: Tue Feb 15, 2005 12:50 Post subject: |
|
|
For future reference, while RAND() works in MySQL, if your using SQLite you need random() instead. Otherwise this does exactly as it says on the tin.
One other question, anyone got any suggestions for a weighted random? I could use multiple entires, but that gets messy for updates. Any better suggestions? |
|
Back to top |
|
|
NoMercy
Joined: 03 Jan 2005 Posts: 123 Location: UK
|
Posted: Tue Feb 15, 2005 14:53 Post subject: |
|
|
Bit harder:
Code: | SELECT * FROM table ORDER BY ( table.weight + RAND() * 100 ) DESC LIMIT 1 |
|
|
Back to top |
|
|
Xildjian
Joined: 08 Jan 2005 Posts: 100
|
Posted: Sun Mar 06, 2005 22:24 Post subject: |
|
|
I'm using the access ODBC db, and this doesn't seem to work for me. What I'm trying to do is this.
I have a table of gems with fields: tag, gp, and name
What I would like to do is grab the tag, from a random row where gp<=somevalue.
I tried something like:
Code: | SELECT tag FROM mytable WHERE gp<=somevalue ORDER BY RAND() LIMIT 1 |
I get the following error in the ODBC log:
Code: | syntax error (missing operator) in query expression 'RAND() LIMIT 1'. |
Any suggestions as I'm pretty clueless at this db stuff at the moment.
Thanks. _________________ Member Shadow of Iniquity development team |
|
Back to top |
|
|
Primogenitor
Joined: 08 Jan 2005 Posts: 88
|
Posted: Mon Mar 07, 2005 10:11 Post subject: |
|
|
Try these:
Rand()
Random()
random()
rand()
RANDOM()
RAND()
Dont know which one works, but one of them probably will |
|
Back to top |
|
|
Xildjian
Joined: 08 Jan 2005 Posts: 100
|
Posted: Mon Mar 07, 2005 15:19 Post subject: |
|
|
Thanks, I did try RANDOM() and RAND() before your post. I then switch over to mySQL and it appears to be working.
Thanks! _________________ Member Shadow of Iniquity development team |
|
Back to top |
|
|
|