php - 如何显示表数组中的最高 ID

标签 php mysql

目前我正在使用这个:

<div class="post-detail">
    <?php
        if($_SESSION["ses"]=="")
        {
            $cont="SELECT * FROM content WHERE id < ( SELECT MAX( id ) FROM content) ORDER BY id desc limit 1"; 
            $cont_row=mysql_query($cont);
            $cont_res=mysql_fetch_assoc($cont_row);

    ?>
    <h3 class="post-title"><?php echo $cont_res["page_title"]?></h3>
    <p class="post-description">
        <?php
            echo $cont_res["details"];
        ?>
    </p>
        <?php } ?>
    <div class="read-more">
        <a href="detail.html">Вижте повече...</a>
    </div>
    <div class="sign-up"></div> 
</div>

但我想显示表内容中具有最高 id 的数组。 我已经尝试过使用 max,但它不工作并给我一些错误:

<?php
    if($_SESSION["ses"]=="")
    {
        $cont="select * from content  where id='MAX(id)'";
        //echo $cont;
        //exit;
        $cont_row=mysql_query($cont);
        $cont_res=mysql_fetch_assoc($cont_row);
    }

?>

这根本不起作用。有人可以展示在表内容中显示数组最高 ID 的正确方法吗?

最佳答案

最好和最简单的答案是对数据进行排序,然后限制返回值。 @shubham 在这个答案的第一行就这样做了,并将其扩展以涵盖您的评论,也只需使用 limit
的偏移量参数 像这样:

// Returns the second highest ID (skip 1)
SELECT id, name, data FROM content ORDER BY id DESC LIMIT 1,1

// Return the top 3
SELECT id, name, data FROM content ORDER BY id DESC LIMIT 3

// Return sixth to eighth place.
SELECT id, name, data FROM content ORDER BY id DESC LIMIT 5, 3

编辑:来自数据库的示例:

mysql> select id,created FROM task ORDER by ID DESC limit 1;
+------+---------------------+
| id   | created             |
+------+---------------------+
| 7602 | 2016-09-23 12:28:04 |
+------+---------------------+
1 row in set (0.00 sec)

mysql> select id,created FROM task ORDER by ID DESC limit 1,1;
+------+---------------------+
| id   | created             |
+------+---------------------+
| 7601 | 2016-09-23 10:01:36 |
+------+---------------------+
1 row in set (0.00 sec)

mysql> select id,created FROM task ORDER by ID DESC limit 5,3;
+------+---------------------+
| id   | created             |
+------+---------------------+
| 7597 | 2016-09-22 12:56:49 |
| 7596 | 2016-09-22 12:41:44 |
| 7595 | 2016-09-22 11:22:02 |
+------+---------------------+
3 rows in set (0.00 sec)

所以,如您所见,这是有效的。

关于php - 如何显示表数组中的最高 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39659183/

相关文章:

php - 这个preg_match语法匹配什么 ".+?"

php - MySQL MAX CONNECTIONS PER HOUR 最优值

php - 用于 Mysql 数据库安全的 Angular 和 Slim 框架

java - MySQL : Communication Link failure error and telnet localhost 3306 : Connection close

mysql错误:The user specified as a definer ('mysql.infoschema' @'localhost' ) does not exist' when trying to dump tablespaces

PHP:未使用 stream_socket_client() 设置 TLS 套接字

PHP MySQL Error echo insert into values 打印在屏幕上

php - 选择框不保留值

php - 如何修复 MediaWiki 错误 "Wiki uses cookies to log in users. You have cookies disabled. Please enable them and try again."?

php - 检查 MySQL 连接 (OOP PHP)