开发者

How can I get the last row value with MySQL?

I have a table called Live, and in the table I have public_id. In public_id are numbers (e.g. 1,2,3,4,5). How can I get the highest number or the last entry's num开发者_JAVA百科ber?


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
$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
}
?>


SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1;

would give you the highest number

Edit: For the php

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


Another option is to use MAX, ie

SELECT MAX(public_id) FROM Live


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:

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

edit:

Here is how you will do it in 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜