Saturday, January 9, 2010

Sort results by chance in MySql

The MySql function rand () can query a random sequence of results in Mysql. If we add to these in his "order by" clause is a chance the results will be sorted. The whole looks like this:

select * from tabellenname order by rand()

It is for larger results note the following: As with any MySql functions will be executed within a query also affects rand () negatively on the performance out. If the result returns only a few lines, it is no problem with safety. At 1,000 or 10,000 records, the query has been delayed by a few 100ths of seconds. That may be at first glance, not much in performance-critical applications, or those that have many simultaneous requests, develops this circumstance, however, a drawback.

In such cases, it offers the chance to insert themselves in to sort table another column. For these will be provided as data type double and set a corresponding index. The insert command must be supplemented in each case:

insert into tabellenname set feld1=’wert1′, feld2=’wert2′, random=rand();

If you sort it directly via the index random field, the query is working much faster. However, it should first be considered whether the sorting of the new field is not ultimately prove to be disadvantageous. That would be the case if the query is used only rarely, and the MySql Server but little memory is available. For then the additional index may unnecessarily block the memory, the other queries need more necessary.

No comments:

Post a Comment