目前我正在使用它:
<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的正确方法吗?
答案 0 :(得分:1)
试试这个
SELECT * from content ORDER BY id DESC LIMIT 1;
如果你只想要一个这样的行,那么
SELECT row from content ORDER BY id DESC LIMIT 1
或
SELECT * FROM content WHERE id = (SELECT MAX(id) FROM content);
答案 1 :(得分:1)
如果您想使用聚合功能,您也可以使用
进行过滤select * from content having id=MAX(id);
在结果集上工作..而不是在表格行上工作
答案 2 :(得分:1)
最好和最简单的答案是对数据进行排序,然后限制返回的值。 @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)
所以,正如你所看到的那样有效。