简体   繁体   中英

MySQL - Selecting random row without repeating

I have a website that gets a random movie from database and then shows it to you. I want to select it without repeating(showing one movie few times while other movies aren't shown) and have it done in the fastest way.

This is what do I have:

$db = new mysqli($DBhost, $DBuser, $DBpassword, $DBdatabase);
$offset_result = " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM database";
$result = $db->query($offset_result);
$offset_row = $result->fetch_object();
$offset = $offset_row->offset;

$db = new mysqli($DBhost, $DBuser, $DBpassword, $DBdatabase);
$query = "SELECT id, title, year, front_image, category, watched, description, imdb_code, bg_image, scene_warning FROM database LIMIT $offset,1";
$stmt = $db->query($query);
list($id, $mtitle, $myear, $front_image, $category, $watched, $description, $imdb_code, $bg_image, $warning)=$stmt->fetch_row();

That is selecting but with repeating... Without repeating, I have this but it's slow.

$db = new mysqli($DBhost, $DBuser, $DBpassword, $DBdatabase);
$query = "SELECT id, title, year, front_image, category, watched, description, imdb_code, bg_image, scene_warning FROM a358_filmovi WHERE id NOT IN (".$movies_array.") ORDER BY rand() LIMIT 1";
$stmt = $db->query($query);
list($id, $mtitle, $myear, $front_image, $category, $watched, $description, $imdb_code, $bg_image, $warning)=$stmt->fetch_row();

$movies_array is imploded session array which contains movie IDs.

So, the question is, how to make a query same as first one (the fastest one) but with an array that contains IDs so movies won't repeat?

为什么不先将所有ID放入会话数组中,选择一个随机索引,查找它,然后从会话数组中删除该索引?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM