0

So, let's say I've got a queryable database with 100 data objects in it. I want to show 3 random ones.

I don't have any working code since this is an idea I just had.

Method 1:

  • Query Database for 3 random ids using mt_rand()

so essentially Query for IDs (1, 15, 67) then print each one.

OR

Method 2:

  • Use mt_rand() in the loop with a counter ($counter = 0; $counter = ++$counter)

essentially Query ALL posts if (ID = 1, 15, 67) then print each one and if ($counter = 3){ break; }

Method 2 sounds like it would give me a nasty large object. While Method 1 sounds like it would be a more expensive DB query. I think Method 1 would be better, but I'm not sure

4

3 に答える 3

3

ID列にインデックスが付けられている場合は、おそらくそうあるべきですが、selectを実行します

WHERE id IN (1, 15, 67)

非常に安いです。また、テーブルにさらに多くの行がある場合でもスケーリングされます。ソリューション 2 は、テーブル全体を選択してメモリにロードするため、スケーリングされません。

于 2013-01-25T18:16:26.977 に答える
3

方法1の方が優れていると確信しています:

方法 1 では、db エンジンはすべての投稿を繰り返し処理して必要なものを見つけ、選択した 3 つの投稿のみを送信します。方法 2 では、db エンジンもすべての投稿を反復処理し、(すべての投稿を含む) より大きなオブジェクトを送信しますが、これには確かにより多くの時間がかかります。

これがお役に立てば幸いです;)

于 2013-01-25T18:16:37.780 に答える
1

明らかに方法1。インデックスが適切に設定されていれば、より高価な DB クエリにはなりません。

あなたが本当に興味があるなら、あなた自身の答えを見つけることができます:

<?
$start = microtime();
doMethodOne();
$end = microtime();

echo 'Method 1 took ' . $end - $start . ' ms<br />';

$start = microtime();
doMethodTwo();
$end = microtime();

echo 'Method 2 took ' . $end - $start . ' ms';
于 2013-01-25T18:16:29.790 に答える