如何在 MySQL 中选择 ID 最高的行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6881424/
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 can I select the row with the highest ID in MySQL?
提问by user870380
How can I select the row with the highest ID in MySQL? This is my current code:
如何在 MySQL 中选择 ID 最高的行?这是我当前的代码:
SELECT * FROM permlog WHERE max(id)
Errors come up, can someone help me?
出现错误,有人可以帮助我吗?
回答by badbod99
SELECT * FROM permlog ORDER BY id DESC LIMIT 0, 1
回答by TD_Nijboer
if it's just the highest ID you want. and ID is unique/auto_increment:
如果它只是您想要的最高 ID。并且 ID 是唯一的/auto_increment:
SELECT MAX(ID) FROM tablename
回答by mu is too short
For MySQL:
对于 MySQL:
SELECT *
FROM permlog
ORDER BY id DESC
LIMIT 1
You want to sort the rows from highest to lowest id
, hence the ORDER BY id DESC
. Then you just want the first one so LIMIT 1
:
您希望将行从最高到最低排序id
,因此ORDER BY id DESC
. 那么你只想要第一个,所以LIMIT 1
:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement.
[...]
With one argument, the value specifies the number of rows to return from the beginning of the result set
LIMIT 子句可用于限制 SELECT 语句返回的行数。
[...]
使用一个参数,该值指定从结果集的开头返回的行数
回答by Mohammad Khan
SELECT *
FROM permlog
WHERE id = ( SELECT MAX(id) FROM permlog ) ;
This would return all rows with highest id
, in case id
column is not constrained to be unique.
这将返回所有具有最高的行id
,以防id
列不限制为唯一。
回答by GemsFord
SELECT MAX(ID) FROM tablename LIMIT 1
Use this query to find the highest ID in the MySQL table.
使用此查询在 MySQL 表中查找最高 ID。
回答by Carlos Utrera
This is the only proposed method who actually selects the whole row, not only the max(id) field. It uses a subquery
这是唯一提出的实际选择整行的方法,而不仅仅是 max(id) 字段。它使用子查询
SELECT * FROM permlog WHERE id = ( SELECT MAX( id ) FROM permlog )
SELECT * FROM permlog WHERE id = (SELECT MAX(id) FROM permlog)
回答by Indu Gauchan
SELECT MAX(id) FROM TABELNAME
从 TABELNAME 中选择 MAX(id)
This identifies the largest id and returns the value
这标识最大的 id 并返回值
回答by Nitin Nath Giri
Suppose you have mulitple record for same date or leave_type but different id and you want the maximum no of id for same date or leave_type as i also sucked with this issue, so Yes you can do it with the following query:
假设您有多个相同日期或 leave_type 但不同 id 的记录,并且您想要相同日期或 leave_type 的最大 id 数,因为我也遇到了这个问题,所以是的,您可以使用以下查询来做到这一点:
select * from tabel_name where employee_no='123' and id=(
select max(id) from table_name where employee_no='123' and leave_type='5'
)