php 如何使用 MySQL 获取最后一行值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7313198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:27:33  来源:igfitidea点击:

How can I get the last row value with MySQL?

phpmysqlinsert

提问by John Doe

I have a table called Live, and in the table I have public_id. In public_idare numbers (e.g. 1,2,3,4,5). How can I get the highest number or the last entry's number?

我有一张桌子叫Live,在桌子上我有public_id。输入的public_id是数字(例如 1,2,3,4,5)。如何获得最高数字或最后一个条目的数字?

回答by santiagobasulto

I'd choose

我会选择

SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1;

It has already been posted, but i'll add something more:

它已经发布了,但我会添加更多内容:

If you perform this query usually you can create an index with inverted ordering.

如果您通常执行此查询,您可以创建一个反向排序的索引。

Something like:

就像是:

CREATE INDEX ON Live (public_id DESC) 

Please Note

请注意

DESC

发展研究中心

PHP + MySQL code:

PHP + MySQL 代码:

<?php
$result = mysql_query('SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1;');
if (mysql_num_rows($result) > 0) {
   $max_public_id = mysql_fetch_row($result);
   echo $max_public_id[0]; //Here it is
}
?>

回答by Mobius

SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1;

would give you the highest number

会给你最高的数字

Edit: For the php

编辑:对于 php

$conn = mysql_connect(....
$query = "SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1";
$result = mysql_query($query, $conn);

回答by ain

Another option is to use MAX, ie

另一种选择是使用MAX,即

SELECT MAX(public_id) FROM Live

回答by ludesign

You can either use ORDER BY public_id DESC LIMIT 1;to obtain the record with the highest id (I guess you are using autoincrement attribute on public_id) or MySQL MAX()function like this:

您可以使用ORDER BY public_id DESC LIMIT 1;获取具有最高 id 的记录(我猜您在 public_id 上使用 autoincrement 属性)或这样的MySQL MAX()函数:

SELECT * FROM table WHERE public_id = MAX(public_id);

edit:

编辑:

Here is how you will do it in php:

以下是您将如何在 php 中执行此操作:

// executing the QUERY request to MySQL server, mysql_query() returns resource ID
$result = mysql_query('SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1');
// then we use this resource ID to fetch the actual value MySQL have returned
$row = mysql_fetch_array($result, MYSQL_FETCH_ASSOC);
// $row variable now holds all the data we got from MySQL, its an array, so we just output the public_id column value to the screen
echo $row['public_id']; // you can use var_dump($row); to see the whole content of $row