2 Replies - 429 Views - Last Post: 06 December 2012 - 07:47 AM

#1 hwoarang69  Icon User is offline

  • D.I.C Head

Reputation: -1
  • View blog
  • Posts: 171
  • Joined: 23-October 12

remove rand method in php query

Posted 06 December 2012 - 12:44 AM

i have this sql query in my home page. problem is that i am using a rand method and if the database is large it will take forever to load up page.

$item_query = mysql_query("SELECT * FROM item ORDER BY RAND() LIMIT 6"); 


i was reading this: http://www.endyourif...-rand-or-newid/

and it talk about doing same thing without using rand method. but i was having hard time understanding it. can any one explain it to me ?

Is This A Good Question/Topic? 0
  • +

Replies To: remove rand method in php query

#2 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9570
  • View blog
  • Posts: 36,242
  • Joined: 12-June 08

Re: remove rand method in php query

Posted 06 December 2012 - 07:46 AM

You want me to exec summarize it? Ah.. okay.

Solution 1 - get a tally of all your rows, get a random number between 1 and that row count, and pull out X of those rows you need. This all assumes your row ids are an auto incrementing integer with no deletes (creating gaps and less than X rows returned).

Solution 2 - create a cron job that seeds your rows (presumably with a new 'rand' column) every so often an then just select X from those.
Was This Post Helpful? 0
  • +
  • -

#3 no2pencil  Icon User is offline

  • Admiral Fancy Pants
  • member icon

Reputation: 5388
  • View blog
  • Posts: 27,384
  • Joined: 10-May 07

Re: remove rand method in php query

Posted 06 December 2012 - 07:47 AM

Assuming your db is indexed properly, select count(id), & get the total, rand off a range of 0 to that count number, then just select that id from the database.

That's how I would do it.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1