任何人都可以告诉我是否可以根据每行的重要性获取mysql条目列表。假设我在表中有4个条目(id,name,importance)。 0 =最高重要性。
id | file | importance
---|-----------|-----------
1 | movie.mp4 | 0
2 | image.jpg | 1
3 | movie1.mp4| 2
4 | movie2.mp4| 2
想要创建一个包含20个enteries的数组,这些数组使用4个元素的结果进行组合(例如5 * movie.mp4,3 * image.jpg,2 * ...,2 * ...),但是技巧是元素必须随机放置在数组中而不是相互之后。
$file[] = movie.mp4;
$file[] = movie2.mp4;
$file[] = image.jpg;
$file[] = movie.mp4;
$file[] = image.jpg;
$file[] = movie1.mp4;
$file[] = movie.mp4;
$file[] = image.jpg;
$file[] = movie.mp4;
$file[] = movie1.mp4;
$file[] = movie.mp4;
$file[] = movie2.jpg;
希望你明白这一点,否则请问:)
答案 0 :(得分:1)
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 );
答案 1 :(得分:0)
我们可以用php简单地完成:
<?php
function cmpf(a,b)
{
return a['importance'] - b['importance'];
}
$arr = array();
$res = mysql_query("SELECT * from tbname ORDER BY importance;");
$k = 0;
while ($row = mysql_fetch_assoc($res))
{
$arr[$k] = $row;
$k++
}
shuffle($arr);
usort($arr, "cmpf");
?>