2015-10-19 345 views
0

我想在mysql中获取最后一行的特定id。让假设我有一个表用户的产品如何获取mysql中最后一行特定的id?

userProducts 

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

我想要得到的user_id=12最后一行Webcame。请指导我如何自定义此查询。

select * from userProducts where user_id = 12 
+2

使用'ORDER BY ID DESC LIMIT 1' –

回答

5

您需要通过ID和限制结果集进行排序:

SELECT * 
FROM userProducts 
WHERE user_id = 12 
ORDER BY id DESC 
LIMIT 1 
-3

添加子查询:

select * from userProducts 
where user_id = 12 
and id = (
select max(id) from userProducts where user_id = 12 
); 
相关问题