[英]Get Last Entry in a MySQL table
I'm basically trying to make a "goal" bar.我基本上是在尝试制作一个“目标”栏。 The goal is determined by getting the last entry I made in a MySQL table.
目标是通过获取我在 MySQL 表中所做的最后一个条目来确定的。 I want to get the ID of the last entry therefore.
因此,我想获取最后一个条目的 ID。
How do I get the last entry in the table and then get the id from that last entry?如何获取表中的最后一个条目,然后从最后一个条目中获取 id?
(Using PHP) (使用 PHP)
To get the greatest 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
you can use LAST_INSERT_ID()
function. 您可以使用
LAST_INSERT_ID()
函数。 example: 例:
$sql = "SELECT * FROM mytable WHERE id = LAST_INSERT_ID()";
您可以使用此查询来获取您希望使用此示例中使用的SQL查询所需的结果:
$sql = "SELECT user_id FROM my_users_table ORDER BY user_id DESC LIMIT 0,1";
如果该字段是自动递增的,那么您可以使用LAST_INSERT_ID
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". 然后,让我们假设它是一个名为“rec_seq”的序列号。 You'd write something like:
你会写一些类似的东西:
select * from my_table
where rec_seq=(select max(rec_seq) from my_table)
以相反的顺序从表中选择所有字段并设置限制0,1这将为您提供表字段数据的最后结果
获取用户的最新条目
'SELECT user_id FROM table_name WHERE user_id = '.$userid.' ORDER BY user_id DESC LIMIT 1';
The above answers show how to get the latest entry by id.上面的答案显示了如何通过 id 获取最新条目。 If one uses non-incrementing ids such as UUIDs as keys, this does not work.
如果使用非递增 ID(例如 UUID)作为键,这将不起作用。 In that case one could use a
created_at
column instead.在那种情况下,可以改用
created_at
列。
-- highest id
SELECT * FROM some_table ORDER BY id DESC LIMIT 1;
-- latest created at date
SELECT * FROM some_table ORDER BY created_at DESC LIMIT 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.