7

i was using order by rand() to generate random rows from database without any issue but i reaalised that as the database size increase this rand() causes heavy load on server so i was looking for an alternative and i tried by generating one random number using php rand() function and put that as id in mysql query and it was very very fast since mysql was knowing the row id but the issue is in my table all numbers are not availbale.for example 1,2,5,9,12 like that.

if php rand() generate number 3,4 etc the query will be blank as there is no id with number 3 , 4 etc.

what is the best way to generate random numbers preferable from php but it should generate the available no in that table so it must check that table.please advise.

$id23=rand(1,100000000);
    SELECT items FROM tablea where status='0' and id='$id23' LIMIT 1

the above query is fast but generate sometimes no which is not availabel in database.

    SELECT items FROM tablea where status=0 order by rand() LIMIT 1

the above query is too slow and causes heavy load on server

4

4 に答える 4

8

DB を使用してテーブルから最大値を見つけ、その値以下の乱数を生成し、id が乱数以上の最初の行を取得します。PHP は必要ありません。

SELECT items
FROM tablea
WHERE status = '0' and
      id >= FLOOR(1 + RAND() * (SELECT MAX(id) FROM tablea))
LIMIT 1
于 2013-01-15T03:56:25.600 に答える
8

まず、100000000 ではなく、1 から MAX(id) までのランダムな値を生成します。

次に、少なくともいくつかの適切な解決策があります。

  1. 使用し>ない=

    SELECT items FROM tablea where status='0' and id>'$id23' LIMIT 1
    

    インデックスを作成し(status,id,items)て、これをインデックスのみのクエリにします。

  2. を使用=しますが、ヒットが見つからない場合は別のランダム値で再試行してください。場合によっては数回試行する必要がありますが、多くの場合、1 回だけ試行します。主=キーを使用できるため、より高速になるはずです。そして、その方が速く、1 回の試行で 90% の確率で成功する場合、1 回以上の試行が必要な残りの 10% の確率を補うことができます。ID値にいくつのギャップがあるかによって異なります。

于 2013-01-15T03:49:33.417 に答える
1

考えられる解決策は、制限を使用することです。

$id23=rand(1,$numberOfRows);

SELECT items FROM tablea where status='0' LIMIT $id23 1

これにより、欠落した行が生成されることはありません(ただし、hek2mgl が述べたように)選択の行数を知る必要があります。

于 2013-01-15T03:52:30.433 に答える
1

ORDER BY RAND()大規模なデータセットを扱っている場合、正しい解決策ではありません。ランダム化する必要がある頻度に応じて、乱数を使用して列を生成し、定義済みの間隔でその数を更新することができます。

その列を取得し、それをソート インデックスとして使用します。これは、負荷の高い読み取り環境でうまく機能し、一定期間、予測可能なランダムな順序を生成します。

于 2013-01-15T03:47:09.227 に答える