如何使用 SQL 语法从 MySQL 表中选择最后一条记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2659253/
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
How to select the last record from MySQL table using SQL syntax
提问by Vonder
I have a table with several records. There is an id field. I would like to select the record with the most recent id (i.e. the highest id).
我有一张有几条记录的表。有一个 id 字段。我想选择具有最新 id(即最高 id)的记录。
Any ideas?
有任何想法吗?
回答by codaddict
SELECT *
FROM table_name
ORDER BY id DESC
LIMIT 1
回答by Andrew Bezzub
User order by with desc
order:
用户按desc
顺序排序:
select * from t
order by id desc
limit 1
回答by Luiz Vid
You could also do something like this:
你也可以做这样的事情:
SELECT tb1.* FROM Table tb1 WHERE id = (SELECT MAX(tb2.id) FROM Table tb2);
Its useful when you want to make some joins.
当您想进行一些连接时,它很有用。
回答by Nikko Domingo
SELECT MAX("field name") AS ("primary key") FROM ("table name")
example:
例子:
SELECT MAX(brand) AS brandid FROM brand_tbl
回答by yassin
SELECT *
FROM table
ORDER BY id DESC
LIMIT 0, 1
回答by Safeer Ahmed
I have used the following two:
我使用了以下两个:
1 - select id from table_name where id = (select MAX(id) from table_name)
2 - select id from table_name order by id desc limit 0, 1
回答by JDK Ben
SELECT * FROM your_table ORDER BY id ASC LIMIT 0, 1
The ASC
will return resultset in ascending order thereby leaving you with the latest or most recent record. The DESC
counterpart will do the exact opposite. That is, return the oldest record.
该ASC
会在升序从而留下您提供最新的或最近的战绩返回结果集。该DESC
副本会做的正好相反。也就是说,返回最旧的记录。