How can I select the row with the highest ID in My

2020-02-18 03:34发布

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?

标签: mysql
8条回答
Luminary・发光体
2楼-- · 2020-02-18 03:39

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

查看更多
家丑人穷心不美
3楼-- · 2020-02-18 03:39
SELECT MAX(ID) FROM tablename LIMIT 1

Use this query to find the highest ID in the MySQL table.

查看更多
Luminary・发光体
4楼-- · 2020-02-18 03:47

SELECT MAX(id) FROM TABELNAME

This identifies the largest id and returns the value

查看更多
唯我独甜
5楼-- · 2020-02-18 03:53

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

SELECT MAX(ID) FROM tablename
查看更多
Deceive 欺骗
6楼-- · 2020-02-18 03:56

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 )

查看更多
三岁会撩人
7楼-- · 2020-02-18 03:56

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'
)
查看更多
登录 后发表回答