Satch3000
Satch3000

Reputation: 49412

PHP MySQL - Select the ID with the highest number

I have a table where multiple records can be stored by the same user on a daily basis.

So right now I'm doing this:

SELECT * FROM `mytable` WHERE user_id = '$userid'

Now, what I need to do is to select the latest entry available by that user, something like:

The table has an ID field which is auto increment so, I was thinking something like:

SELECT * FROM `stats` WHERE user_id = '$userid' WHERE ID <- Is the latest..

How can I do that and select Where ID is the latest ?

Upvotes: 0

Views: 67

Answers (3)

Vishal
Vishal

Reputation: 46

try this query.

SELECT * FROM mytable WHERE postID=(SELECT MAX(userID) FROM mytable)

Upvotes: 0

Kevin Lab&#233;cot
Kevin Lab&#233;cot

Reputation: 1995

You can do a subquery.

SELECT * FROM `stats` WHERE user_id = '$userid' WHERE ID = (SELECT MAX(ID) FROM your_table)

See Abhik Chakraborty's answer if the higher ID you search is from the "stats" table. It's answer is a lot better :)

Upvotes: 3

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44864

How about

SELECT * 
FROM `stats` 
WHERE user_id = '$userid'
order by ID desc limit 1

Upvotes: 5

Related Questions