1

Mysqlでは、クエリからこの種の結果が得られます

+-id-+-name--+is_active-+---date---+
|  1 | name1 |     1    | 21231321 |
|  3 | name3 |     1    | 11313213 |
|  4 | name9 |     1    | 10313213 |
|  8 | name3 |     1    | 10013213 |
| 54 | name2 |     0    |    0     |
| 9  | name5 |     0    |    0     |
| 11 | name8 |     0    |    0     |

このクエリを再度選択せずに、この結果クエリから複数の選択を行いたい。

上記の結果クエリから、この3つの条件を1つに抽出したいと思います

1.Give me first two rows (result query above is sorted by date)
2.Give me one random row where is_active = 1 and not in results in 1.
3.Give me one random row where  is_active = 0

database viewsとについて読みましstored proceduresたが、これが最善の方法かどうかわかりませんか?

誰かが私にこのためのMySQLコードを提供できますか?

ありがとう

4

1 に答える 1

2

コメントに記載されているように、50〜100行の小さな結果セットの場合、PHPの配列処理機能は要件を非常に簡単に処理できます。行セットがクエリ出力でソートされていると仮定します

ORDER BY 
 date DESC,
 is_active DESC

...使用しているAPIを使用して、PHPですべての行を1つの配列にフェッチできます。

// To store output:
$results = array();

// Using the appropriate fetch call (assuming an associative array here)
while ($row = $result_resource->fetch()) {
  // append row onto results
  $results[] = $row;
}

// Remove the first 2 - your first requirement:
$first_two = array_splice($results, 0, 2);

$active = array();
$inactive = array();
// Then split the remaining into is_active or not is_active with a loop
foreach ($results as $r) {
  if ($r['is_active'] == 1) {
    $active[] = $r;
  }
  else $inactive[] = $r;
}

// Then you can just call `array_rand()` to get results from those
$rand_active = array_rand($active);
$rand_inactive = array_rand($inactive);

これはすべて、行セットが小さいことに依存していることをもう一度述べます。配列とループのオーバーヘッドは、おそらく複数のクエリ呼び出しよりも少なくなります。ただし、行セットが大きい場合は、3つの個別のクエリを使用します。

最初:

ORDER BY 
  date DESC
  is_active DESC
LIMIT 2

そのクエリから行を取得し、IDを取得します。次のコマンドで再実行します。

WHERE
  is_active = 1 
  /* the 2 ids from the first query */
  AND id NOT IN (id1, id2)
ORDER BY RAND()
LIMIT 1

そして3番目のクエリ:

WHERE is_active = 0
ORDER BY RAND() 
LIMIT 1

これら3つすべてを1つのクエリにまとめることができUNION ALLますが、パフォーマンスが本当に悪い場合にのみ考えます。

于 2013-01-27T13:01:41.463 に答える