Jump to content

A Good Solution To Not Use Order By Rand()


beyzad

Recommended Posts

Hi there.

 

I need a query to get 20 random data from my database using some conditions.

 

So here is my code:

 

<?php
$max = single_field_q("SELECT MAX(`ads_product_id`) FROM `ads_products`");
$rand = rand(20 , $max);
$products = multi_row_q("SELECT * FROM `ads_products` WHERE `ads_product_id`<" . $rand . " ORDER BY `ads_product_id` DESC LIMIT 20");
?>

 

It will work very well. But if i use my conditions, This will sometimes returns less than 20 results. And sometimes zero results :shrug:

 

I know why it returns less than 20. Now i need a solution for this.

 

Thanks.

Edited by beyzad
Link to comment
Share on other sites

Your code is not getting 20 random products. It is getting a block of upto 20 products ending at a random product id.

 

If you have removed a number of earlier product id's, when $rand is a low value, there aren't enough product id's that are less-than $rand.

 

If you truly want 20 random products, retrieve all your product id's into an array. shuffle the array, then use array_slice to get 20 of the id's, then implode them and use them in an IN() statement in one query.

Edited by PFMaBiSmAd
Link to comment
Share on other sites

I was going to comment earlier that the way I do it is select every ID into an array, use array_rand or shuffle, then do another query using only those IDs. However I wasn't sure if there was a more elegant approach. If PFM is recommending that approach I feel okay about it too.

Link to comment
Share on other sites

Hi again.

 

I was thinking about this:

 

there are 2 methods for what i want:

 

1- Using ORDER BY RAND()

2- Using the method that 'PFMaBiSmAd' said.

 

In both methods above, ALL fields from that table will be selected, then 20 of them will be exported randomly. The difference is in first method, MySQL Will select random rows and in second method, PHP will do that. Plus in the second method, we have 1 more condition in our query.

 

Is the second method better than first by the way?

 

Thanks

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.