开发者

How to order results of a query randomly & select random rows. (MySQL)

开发者 https://www.devze.com 2023-02-22 20:05 出处:网络
Please note I am a beginner to this. I have two questions: 1) How can I order the results of a query randomly.

Please note I am a beginner to this.

I have two questions:

1) How can I order the results of a query randomly.

example query:

$get_questions = mysql_query("SELECT * FROM item_bank_tb WHERE item_type=1 OR item_type=3 OR item_type=4");

2) The best method to select random rows from a table. So lets say I want to grab 10 rows at random from a table.

Ma开发者_C百科ny thanks,


If you don't mind sacrificing complexity on the insert/update/delete operations for speed on the select, you can always add a sequence number and make sure it's maintained on insert/update/delete, then whenever you do a select, simply select on one or more random numbers from within this range. If the "sequence" column is indexed, I think that's about as fast as you'll get.

An alternative is "shuffling". Add a sequence column, insert random values into this column, and whenever you select records, order by the sequence column and update the selected record sequences to new random values. The update should only affect the records you've retrieved, so shouldn't be too costly ... but it may be worth running some tests against your dataset.

This may be a fairly evil thing to say, but I'll say it anyway ... is there ever a need to display 'random' data? if you're trying to display random records, you may be doing something wrong.

Think about Amazon ... do they display random products, or do they display popular ones, and 'things other people bought when they looked at this'. Does SO give you a list of random questions to the right of here, or a list of related ones? Just some food for thought.


SELECT * FROM item_bank_tb WHERE item_type in(1,3,4) order by rand() limit 10

Beware that order by rand() is very slow on large recordset.

EDIT. Take a look at this very interesting article that presents a different approach.

http://explainextended.com/2009/03/01/selecting-random-rows/

0

精彩评论

暂无评论...
验证码 换一张
取 消