php 获取 MySQL 表中的最后一个条目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10503195/
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-24 22:21:27  来源:igfitidea点击:

Get Last Entry in a MySQL table

phpmysql

提问by ComputerLocus

I'm basically trying to make a "goal" bar. The goal is determined by getting the last entry I made in a MySQL table. I want to get the ID of the last entry therefore.

我基本上是在尝试制作一个“目标”栏。目标是通过获取我在 MySQL 表中创建的最后一个条目来确定的。因此,我想获取最后一个条目的 ID。

How do I get the last entry in the table and then get the id from that last entry?

如何获取表中的最后一个条目,然后从最后一个条目中获取 id?

(Using PHP)

(使用 PHP)

回答by Eric Petroelje

To get the greatest id:

要获得最大的 id:

SELECT MAX(id) FROM mytable

Then to get the row:

然后获取行:

SELECT * FROM mytable WHERE id = ???

Or, you could do it all in one query:

或者,您可以在一个查询中完成所有操作:

SELECT * FROM mytable ORDER BY id DESC LIMIT 1

回答by laltin

you can use LAST_INSERT_ID()function. example:

你可以使用LAST_INSERT_ID()函数。例子:

$sql = "SELECT * FROM mytable WHERE id = LAST_INSERT_ID()";

回答by Rasmus S?borg

you can use this query to get the results you want with this sql query as used in this example:

您可以使用此查询通过此示例中使用的此 sql 查询获得所需的结果:

$sql = "SELECT user_id FROM my_users_table ORDER BY user_id DESC LIMIT 0,1";

回答by Jay

To do this reliably, you must have some field in the table that you can examine to determine which is last. This could be a time stamp of when you added the record, a sequence number that continually increases (especially an auto-incrementing sequence number), etc.

要可靠地做到这一点,您必须在表中有一些字段,您可以检查以确定哪个字段是最后一个。这可能是您添加记录的时间戳、不断增加的序列号(尤其是自动递增的序列号)等。

Then, let's suppose it's a sequence number called "rec_seq". You'd write something like:

然后,假设它是一个名为“rec_seq”的序列号。你会写这样的:

select * from my_table
where rec_seq=(select max(rec_seq) from my_table)

回答by Moyed Ansari

if the field is auto-incremented then you can use LAST_INSERT_ID

如果该字段是自动递增的,那么您可以使用 LAST_INSERT_ID

回答by Puzzled Boy

select all fields from table in reverse order and set limit 0,1 This will give you last result of table field data

以相反的顺序从表中选择所有字段并设置限制 0,1 这将为您提供表字段数据的最后结果

回答by user3917039

Get the latest entry of a user

获取用户的最新条目

'SELECT user_id FROM table_name WHERE user_id = '.$userid.' ORDER BY user_id DESC LIMIT 1';