如何在mysql中获取特定id的最后一行?

时间:2015-10-19 12:28:09

标签: php mysql

我试图在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 个答案:

答案 0 :(得分:6)

您需要按ID排序并限制结果集:

<form id="storeFields" method="post" action="">
    <label>Name:</label>
    <input type="text" name="name" id="name" class="stored" value="" />

    <label>Email:</label>
    <input type="email" name="email" id="email" class="stored" value="" />

    <label>Message:</label>
    <textarea name="message" id="message" class="stored"></textarea>

    <input type="submit" class="demo-button" value="Submit" />
</form>

答案 1 :(得分:-3)

添加子查询:

select * from userProducts 
where user_id = 12 
and id = (
 select max(id) from userProducts where user_id = 12
);