SELECT draw_bucket.file
FROM (
SELECT row,
FLOOR(RAND() * (SELECT SUM(POW(2, 2 - importance)) FROM files)) AS rnd
FROM (
(SELECT 1 AS row) UNION (SELECT 2) UNION (SELECT 3) UNION (SELECT 4) UNION
(SELECT 5) UNION (SELECT 6) UNION (SELECT 7) UNION (SELECT 8) UNION
(SELECT 9) UNION (SELECT 10) UNION (SELECT 11) UNION (SELECT 12) UNION
(SELECT 13) UNION (SELECT 14) UNION (SELECT 15) UNION (SELECT 16) UNION
(SELECT 17) UNION (SELECT 18) UNION (SELECT 19) UNION (SELECT 20)
) AS row_nums
) AS rows
INNER JOIN (
SELECT @row := @row + 1 AS row, file
FROM (
(SELECT 1 AS cnt) UNION (SELECT 2) UNION (SELECT 3) UNION (SELECT 4)
) AS cnt
INNER JOIN files
ON(cnt.cnt <= POW(2, 2 - files.importance))
INNER JOIN (SELECT @row := -1) AS INIT
) AS draw_bucket
ON(rows.rnd = draw_bucket.row)
數(SELECT 1), (SELECT 2), ...
在row_nums
子查詢應該等於你想要的條目數和cnt
子查詢應該等於2^minimumPriority。
您可以通過完成PHP中的大部分工作(例如)來簡化此操作。做一個SELECT *
和填補像這樣的數組:
$items = array(
array('file' => 'movie.mp4', 'importance' => 0),
array('file' => 'image.jpg', 'importance' => 1),
array('file' => 'movie1.mp4', 'importance' => 2),
array('file' => 'movie2.mp4', 'importance' => 2)
);
然後做圖中的PHP:
$minImportance = 2;
$drawBucket = array();
foreach($items as $index => $item) {
for($i = 0; $i < pow(2, $minImportance - $item['importance']); ++$i) {
$drawBucket[] = $index;
}
}
$output = array();
for($i = 0; $i < 20; ++$i) {
$randomIndex = mt_rand(0, count($drawBucket) - 1);
$output[] = $items[ $drawBucket[$randomIndex] ][ 'file' ];
}
var_dump($output);
請重新表述您的問題標題,它無關,與您所提供 – ajreal