如何在mysql中获取特定id的最后一行? [重复]
问题描述:
This question already has an answer here:
- Select last row in MySQL 10 answers
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
</div>
此问题已经存在 这里有一个答案: p>
-
选择MySQL中的最后一行
10 answers
span>
li>
ul>
div>
我正在尝试在mysql中获取特定id的最后一行。 假设我有一个表用户产品 p>
userProducts id | user_id | 产品 1 | 12 | 鼠标 2 | 12 | 键盘 3 | 12 | 笔记本电脑 4 | 12 | 耳机 5 | 12 | Webcame code> pre>
我想获取
user_id = 12 code>的最后一行Webcame。 请指导我如何自定义此查询。 p>
select * from userProducts其中user_id = 12 code> pre> div>
答
You need to sort by id and limit resultset:
SELECT *
FROM userProducts
WHERE user_id = 12
ORDER BY id DESC
LIMIT 1
答
Add a subquery:
select * from userProducts
where user_id = 12
and id = (
select max(id) from userProducts where user_id = 12
);