简体   繁体   中英

How can I select the row with the highest ID in MySQL?

How can I select the row with the highest ID in MySQL? This is my current code:

SELECT * FROM permlog WHERE max(id)

Errors come up, can someone help me?

SELECT * FROM permlog ORDER BY id DESC LIMIT 0, 1

if it's just the highest ID you want. and ID is unique/auto_increment:

SELECT MAX(ID) FROM tablename

For 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 :

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

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.

SELECT MAX(ID) FROM tablename LIMIT 1

使用此查询在 MySQL 表中查找最高 ID。

This is the only proposed method who actually selects the whole row, not only the max(id) field. It uses a subquery

SELECT * FROM permlog WHERE id = ( SELECT MAX( id ) FROM permlog )

SELECT MAX(id) FROM TABELNAME

This identifies the largest id and returns the value

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:

select * from tabel_name where employee_no='123' and id=(
   select max(id) from table_name where employee_no='123' and leave_type='5'
)

Since both SELECT MAX(id) FROM table and SELECT id FROM table ORDER BY id DESC LIMIT 0,1 fulfill the goal, the interesting part is, which performs better.

SELECT MAX(id) FROM table : 152ms
SELECT id FROM table ORDER BY id DESC LIMIT 0,1 : 25ms
(InnoDB-table with 55M rows on MySQL 8.0, 10 runs, average result)

Of course thats not representive, but gives an idea, that the ORDER BY method performs significantly better.

SELECT * FROM `permlog` as one
RIGHT JOIN (SELECT MAX(id) as max_id FROM `permlog`) as two 
ON one.id = two.max_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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