Jump to content

Recommended Posts

I have a basic select statement:

 

SELECT id AS prodId FROM products WHERE (title='kookaburra') ORDER BY RAND() LIMIT 0, 8;

 

from a table containing id,title,description. But of those 8 random results I need to require one record be included IF it's title='emu'.

 

Any way to do this with one SELECT statement or a fancy ORDER BY of some kind? I also tried a subselect but it threw an error... Seems like this should be straightforward enough but I'm a bit stumped.

 

Ideally, I'd want 7 random results + the required one (if it exists), otherwise 8 random results.

 

Any advice?

 

(mysql version 4.1)

Link to comment
https://forums.phpfreaks.com/topic/215420-get-rand-results-with-one-required-row/
Share on other sites

OK, it seemed a little finicky but it totally works. To get 7 random items + 1 specific item:

 

(SELECT id FROM products WHERE (title != 'something specific' AND category='marmalades') ORDER BY RAND() LIMIT 0, 7)
        
        UNION
        
        (SELECT id FROM products WHERE (title='something specific' AND category='marmalades') LIMIT 0, 1);

 

I ended up having to force title != 'something specific' in the first SELECT and then force title = 'something specific' in the second one to achieve the desired result.

 

Unfortunately this doesn't yet allow for getting only 8 random results if no 'something specific' exists but it's a workable solution.

 

Thanks!

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.