Judking
Judking

Reputation: 6371

How to select the record which has the max id in mysql?

Here's the test_table in mysql:

id  |   C
1       c1
2       c1
3       c2

If I use:

select * from test_table

I'll got the records whose id equals 1,2,3

But what I intend to do is to retrieve records with id equals 2 and 3. That is, When field C is the same, retrieve the one who's got the max id.

Could anyone give me some idea? Thanks a lot!

Upvotes: 0

Views: 59

Answers (2)

HengChin
HengChin

Reputation: 593

SELECT MAX(id)
FROM test_table
GROUP BY c

Upvotes: 1

Edper
Edper

Reputation: 9322

You could use GROUP BY and MAX() aggregate function like:

SELECT C, MAX(id) as MaxID
FROM tableName
GROUP BY C

See Fiddle Demo

Upvotes: 2

Related Questions