如何限制“;SELECT”;后果


How to limit "SELECT" results?

我有了下一个代码,他向用户展示了正在制作的新类别。问题是我不知道如何限制结果,并对最后5个类别进行类似的限制?谢谢抱歉英语不好。感谢

   <?php
    $stmt = $pdo->prepare('SELECT * FROM categories');
    $stmt->execute();
    echo $stmt->rowCount();
?>
</span>
</a>
<ul class="dropdown-menu extended notification">
    <li>
        <p>Categories</p>
    </li>
<?php
    if($stmt->rowCount() > 0) {
        foreach($stmt->fetchAll() as $row) {
            $html = '<li>';
            $html .= '<div class="alert alert-info clearfix">';
            $html .= '<span class="alert-icon"><i class="fa fa-flag"></i></span>';
            $html .= '<div class="noti-info">';
            $html .= 'Category #'.$row['CategoryID'].' '.$row['CategoryName'].'';
            $html .= '</div>';
            $html .= '</div>';
            $html .= '</li>';
            echo $html;
        }
    } else {
        $html = '<li>';
        $html .= '<div class="alert alert-danger clearfix">';
        $html .= '<span class="alert-icon"><i class="fa fa-flag"></i></span>';
        $html .= '<div class="noti-info">';
        $html .= '<a href="#"> There are no available categories.</a>';
        $html .= '</div>';
        $html .= '</div>';
        $html .= '</li>';
        echo $html;
    }
?>

在查询中使用ORDER BY、DESC和LIMIT,即:

SELECT * FROM categories ORDER BY ColumnNameEx DESC LIMIT 5;

ORDER BY

在某些情况下,MySQL可以使用索引来满足ORDER BY子句而不需要进行额外的排序
即使ORDER BY与精确索引,只要索引中所有未使用的部分额外的ORDER BY列是WHERE子句中的常量

http://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html


DESC

默认的排序顺序是升序,最小值优先。到按相反(降序)排序,在名称中添加DESC关键字您正在排序的列的。

http://dev.mysql.com/doc/refman/5.7/en/sorting-rows.html


LIMIT

如果只需要结果集中指定数量的行,请使用查询中的LIMIT子句,而不是获取整个结果集并丢弃多余的数据。

https://dev.mysql.com/doc/refman/5.5/en/limit-optimization.html


在查询"LIMIT x"的末尾添加,x是您想要获得的结果数量