我有一个客户,我正在开发一个视频网站。他希望从数据库中提取2个视频,以显示前端用户的投票结果。
视频表有一个“投票”字段。他希望随机提取视频,但对具有更高投票数的视频给予更高的偏好。某种算法,其中投票给予优先权,但不仅仅是直接“最高投票的2个视频被拉动”。
有什么想法吗?
看看我的视频表是什么样的:
$data[] = array(
'id' => $row->id,
'filename' => $row->filename,
'added' => $row->added,
'userId' => $row->userId,
'contestId' => $row->contestId,
'complete' => $row->complete,
'ended' => $row->ended,
'votes' => $row->votes
);
答案 0 :(得分:0)
只需使用一个很好的平衡的ORDER BY votes * ($offset + rand()) DESC
和,其中偏移平衡随机化。如果offset为0,则它大部分是随机的,如果offset为1或更高,则不会显示未投票的视频。
您可以在干跑中尝试几次拍摄的视频,看看是否喜欢它。 ; - )
编辑:
答案取决于数据库中的投票范围和分布。
答案 1 :(得分:0)
考虑以下内容......
SELECT * FROM weighted;
+----+--------+
| id | weight |
+----+--------+
| 1 | 3 |
| 2 | 1 |
| 3 | 6 |
| 4 | 5 |
| 5 | 10 |
| 6 | 2 |
| 7 | 3 |
| 8 | 7 |
| 9 | 7 |
+----+--------+
So, crudely...
SELECT *,RAND()*weight FROM weighted;
+----+--------+--------------------+
| id | weight | RAND()*weight |
+----+--------+--------------------+
| 1 | 3 | 1.7466305203238788 |
| 2 | 1 | 0.6615251914239724 |
| 3 | 6 | 3.3659728051777673 |
| 4 | 5 | 4.102008970549338 |
| 5 | 10 | 4.190225986940997 |
| 6 | 2 | 1.2678152837490806 |
| 7 | 3 | 2.737411332072142 |
| 8 | 7 | 4.624405276611824 |
| 9 | 7 | 3.9601472736896457 |
+----+--------+--------------------+
SELECT *,RAND()*weight x FROM weighted ORDER BY x DESC LIMIT 1;
+----+--------+--------------------+
| id | weight | x |
+----+--------+--------------------+
| 8 | 7 | 4.6799722441285585 |
+----+--------+--------------------+
SELECT *,RAND()*weight x FROM weighted ORDER BY x DESC LIMIT 1;
+----+--------+-------------------+
| id | weight | x |
+----+--------+-------------------+
| 9 | 7 | 5.331623214605845 |
+----+--------+-------------------+
SELECT *,RAND()*weight x FROM weighted ORDER BY x DESC LIMIT 1;
+----+--------+-------------------+
| id | weight | x |
+----+--------+-------------------+
| 4 | 5 | 4.931961209449881 |
+----+--------+-------------------+
SELECT *,RAND()*weight x FROM weighted ORDER BY x DESC LIMIT 1;
+----+--------+-------------------+
| id | weight | x |
+----+--------+-------------------+
| 8 | 7 | 6.230309537826394 |
+----+--------+-------------------+
SELECT *,RAND()*weight x FROM weighted ORDER BY x DESC LIMIT 1;
+----+--------+-------------------+
| id | weight | x |
+----+--------+-------------------+
| 5 | 10 | 5.470934962361059 |
+----+--------+-------------------+