0

I'm trying to get last row of specific id in mysql. Let suppose i have a table user products

    userProducts

    id | user_id  | products 
    1 | 12| Mouse
    2 | 12| Keyboard
    3 | 12| Laptop
    4 | 12| Headphone
    5 | 12| Webcame

I want to get last row Webcame of user_id=12. Please guide me how can i customize this query for that.

select * from userProducts where user_id = 12
Ayaz Ali Shah
  • 634
  • 2
  • 7
  • 16

2 Answers2

7

You need to sort by id and limit resultset:

SELECT * 
FROM userProducts
WHERE user_id = 12
ORDER BY id  DESC
LIMIT 1
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
-3

Add a subquery:

select * from userProducts 
where user_id = 12 
and id = (
 select max(id) from userProducts where user_id = 12
);
Daan
  • 12,099
  • 6
  • 34
  • 51