mysql随机选择最新的15行100行数据

时间:2014-12-26 11:43:57

标签: php mysql random

$sql = "SELECT `url`,`title`,`vid` FROM `video` ORDER BY `time` DESC limit 15";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);

此SQL可以选择最新的15行数据。

我希望显示最新的100,但只显示15

如何更快地选择?

2 个答案:

答案 0 :(得分:1)

$sql = "SELECT `url`,`title`,`vid` FROM `video` ORDER BY `time` DESC limit 100";

我假设$row[0] =>给出了第一条记录。

-

function UniqueRandomNumbersWithinRange($min, $max, $quantity) {
    $numbers = range($min, $max);
    shuffle($numbers);
    return array_slice($numbers, 0, $quantity);
}

-

foreach (UniqueRandomNumbersWithinRange(0,100,15) as $row_number)
{
   $content=$row[$row_number];
   echo $content['title'];
}

答案 1 :(得分:1)

你可以尝试修复它:

<?php
//get the max count for the table;
$max="SELECT id FROM video order by time desc LIMIT 1";
$start="SELECT id FROM video order by time desc LIMIT 100, 1";
$page_size=15;
$rand_no=rand(start,$max - page_size);

$result_set="SELECT * FROM video order by time LIMIT $rand_no,page_size";

NB :这是一个抽象代码解释逻辑。