我有一个名为Live
的表格,在表格中我有public_id
。在public_id
中是数字(例如1,2,3,4,5)。如何获得最高编号或最后一个条目的编号?
答案 0 :(得分:8)
我会选择
SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1;
它已经发布,但我会添加更多内容:
如果通常执行此查询,则可以创建具有反向排序的索引。
类似的东西:
CREATE INDEX ON Live (public_id DESC)
请注意
DESC
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
}
?>
答案 1 :(得分:5)
SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1;
会给你最高的数字
编辑:对于php
$conn = mysql_connect(....
$query = "SELECT public_id FROM Live ORDER BY public_id DESC LIMIT 1";
$result = mysql_query($query, $conn);
答案 2 :(得分:3)
另一种选择是使用MAX
,即
SELECT MAX(public_id) FROM Live
答案 3 :(得分:0)
你可以使用ORDER BY public_id DESC LIMIT 1;
获取id最高的记录(我猜你在public_id上使用autoincrement属性)或MySQL MAX()
这样的函数:
SELECT * FROM table WHERE public_id = MAX(public_id);
编辑:
以下是如何在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