简体   繁体   English

MySQL:如何获得最后一条记录?

[英]MySQL: how to get the last record?

Say I have the following records:假设我有以下记录:

1, A
1, B
2, A
2, B
2, C
1, C

I want the last record for 1 and 2 , which should be 1, C and 2, C .我想要12的最后一条记录,应该是1, C2, C How do I query that?我该如何查询?

If I do a GROUP BY on the number, I get 1, A and 2, A .如果我对号码执行 GROUP BY ,我会得到1, A2, A

if by 'last' you mean maximum alphabetically, then maybe this:如果“最后”是指按字母顺序排列的最大值,那么可能是这样的:

select id, max(val)
from mytable
group by id

Without some sort of index or insertion order, there's no way of getting what you want;如果没有某种索引或插入顺序,就无法得到你想要的; SQL queries are order non-deterministic. SQL 查询是顺序不确定的。

Now that we've established that you mean "last" as in "chronologically", then I can create a proper answer...既然我们已经确定您的意思是“按时间顺序”中的“最后”,那么我可以创建一个正确的答案......

SQL has no concept of chronology. SQL 没有年表的概念。 So you will have to record the insertion order yourself.因此,您必须自己记录广告订单。 Most typically, you would add an autoincrementing field, and then use that in an ORDER BY clause, along with a LIMIT clause.最典型的是,您将添加一个自动递增字段,然后在ORDER BY子句中使用它以及一个LIMIT子句。

If it's not alphabetic, then you need to use LIMIT and so just do the following.如果它不是字母,那么您需要使用 LIMIT ,所以只需执行以下操作。

select @rownum:=@rownum+1 as naturalorder, * from foo, (SELECT @rownum:=0) nat order by naturalorder desc limit 1;

but warning that there is no guarantee from mysql on the order of the records.但警告 mysql 不保证记录的顺序。 so you might want to add an extra field with a timestamp fields or an auto_increment which will have the order that you are looking for, i think.所以你可能想添加一个带有时间戳字段或 auto_increment 的额外字段,这将具有你正在寻找的顺序,我想。

If it is alphabetical, the trick is to order by the code descending and then get the 1st record.如果它是按字母顺序排列的,诀窍是按代码降序排列,然后获得第一条记录。 And you can limit that by one.您可以将其限制为一个。

select num, code from thetable order by code DESC limit 1

if you use group by, you have to scan through the entire table.如果使用 group by,则必须扫描整个表。 and also it's difficult to get the full record.而且很难获得完整的记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM