Reputation: 1496
I have a table that looks similar to this:
images
image_id int
user_id int
datetime datetime
So, I need to get only one result. This result should have a specific user_id and should only be the most recent row in the table.
I've checked out many similar questions, but wasn't able to understand how to do it and the codes I found didn't work at all.
How can I achieve this?
Here's a start query:
SELECT *
FROM image
WHERE user_id = :user_id
How do I change this query to select only the most recent row with a specific user_id?
Upvotes: 0
Views: 1341
Reputation: 412
By using limit you can get no.of required data
limit required_no.
Upvotes: 0
Reputation: 295
Select * from images where User_id = :User_id Order by datetime DESC Limit 1
Hope it works :)
Upvotes: 0
Reputation: 839
For MySQL try the following:
SELECT * FROM image
WHERE user_id = :user_id
ORDER BY datetime DESC limit 1
limit
will work with MySQL
For further info on MySql statements look here: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax.html
Upvotes: 0
Reputation:
For SQL Server you can use:
SELECT TOP(1) *
FROM image
WHERE user_id = :user_id
ORDER BY datetime DESC
Upvotes: 0
Reputation: 4491
You can use order by clause like this:
SELECT *
FROM image
WHERE user_id = :user_id ORDER BY datetime DESC LIMIT 1
Upvotes: 1