Jump to content

Select random row if value is not found


aviddv1

Recommended Posts

[quote author=aviddv1 link=topic=109771.msg442759#msg442759 date=1159400126]
Hey there,

I'm trying to write a query that will select 1 random row from a table only if the value 0 does not exist in a field called random.  If 0 does exist then i want it to return that row instead of randomly selecting one.

thanks,
ward
[/quote]

You should also be able to use the following
[code]
SELECT * FROM tablename ORDER BY IF(random = 0, -1, RAND()) ASC LIMIT 1
[/code]
Link to comment
Share on other sites

[quote author=shoz link=topic=109771.msg442823#msg442823 date=1159410902]
You should also be able to use the following
[code]
SELECT * FROM tablename ORDER BY IF(random = 0, -1, RAND()) ASC LIMIT 1
[/code]
[/quote]
How would that work? Which records would it examine?  And I didn't that that you use an expression in an ORDER BY clause.
Link to comment
Share on other sites

[quote author=fenway link=topic=109771.msg443097#msg443097 date=1159454723]
[quote author=shoz link=topic=109771.msg442823#msg442823 date=1159410902]
You should also be able to use the following
[code]
SELECT * FROM tablename ORDER BY IF(random = 0, -1, RAND()) ASC LIMIT 1
[/code]
[/quote]
How would that work? Which records would it examine?  And I didn't that that you use an expression in an ORDER BY clause.
[/quote]

Just as when you "ORDER BY RAND()" each row is ordered based on the evaluation of the expression. In this case the return value of RAND().

[code]
ORDER BY IF(random = 0, -1, RAND())
[/code]
When MYSQL encounters a row whose "random" field contains the value 0 it will be ordered based on the value -1. Otherwise, the row is ordered based on the value returned by RAND().

Since -1 will be lower than any RAND() (between 0 and 1) value, if a row in the table has a "random" value of 0 it will be first in the result. If not, one of the other fields will be the first in the result and that will be based on the RAND() value.

The LIMIT 1 of course gives us only the first record.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.