【问题标题】:PHP+MySQL: How to fetch just limited count of results?PHP + MySQL:如何获取有限的结果?
【发布时间】:2013-03-07 09:21:54
【问题描述】:

我有一个包含 100-200k 记录的数据库表,我需要对其进行优化。例如,如果用户想要搜索术语 car,他将获得大约 25k 条结果。

我想为他提供 500 条最新结果,但该怎么做?我知道我必须使用LIMIT,但我不确定如何将最新的 500 行“分组”。

为了更好地了解我现在如何从数据库中获取数据,这里有一个小 sn-p:

$search = mysql_real_escape_string(searched_query($_GET['skill'])); 
$q = "...long sql query...";
echo $q;
$result = mysql_query($q);
$items = 30; // number of items per page.
$all = $_GET['a'];

$num_rows = mysql_num_rows($result);
if($all == "all"){
    $items = $num_rows;
}
$nrpage_amount = $num_rows/$items;
$page_amount = ceil($num_rows/$items);
$page_amount = $page_amount-1;
$page = mysql_real_escape_string($_GET['p']);
if($page < "1"){
    $page = "0";
}
$p_num = $items*$page;
// Query that you would like to SHOW
$result = mysql_query($q." ORDER BY published DESC LIMIT $p_num , $items");

提前谢谢你!

【问题讨论】:

    标签: php mysql limit


    【解决方案1】:

    通过published DESC 订购,您已经将列表从最新到最旧排序。所以如果你应用 500 的limit,它会自动只获取最新的 500 行...

    所以Mysql会先order,然后再申请limit。

    【讨论】:

    • @user1946705, MySQL 的 LIMIT IS 分页
    【解决方案2】:

    在查询中使用ORDER BY。查看here了解更多详情

    【讨论】:

    • @saratis :错过了那部分。对不起我的无知
    猜你喜欢
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多