更新MySQL中特定ID的最后一个条目

时间:2012-07-11 09:48:13

标签: mysql database

我有一个表student_log,并且单个'rollno'有多个记录。

'sno'是student_log表的auto_increment索引。

假设我想更新特定学生的最后一个(最近的)条目的特定字段的值(由'rollno'查找),我该怎么做?我目前的做法不起作用。我这样做:

update student_log set timein=current_timestamp() where rollno='ST001' and 
sno = (select sno from student_log where rollno='ST001' order by sno desc limit 1);

使用子查询,我试图检索学生的rollno匹配的最新记录的sno。我正在尝试使用它来匹配sno和更新语句,这不起作用。

我知道语法是正确的,但我认为这只是意味着MySQL不允许更新使用子查询。谢谢。问我是否遗漏了任何信息。

2 个答案:

答案 0 :(得分:7)

UPDATE student_log
SET timein=current_timestamp()
WHERE rollno='ST001'
ORDER BY sno DESC
LIMIT 1

修改 <是/> 测试了我的查询,是的,这是可能的,或者我在OPs表结构中错过了什么

mysql> UPDATE student_log
    -> SET timein=current_timestamp()
    -> WHERE rollno='ST001'
    -> ORDER BY sno DESC
    -> LIMIT 1;
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> SELECT * FROM student_log;
+-----+--------+---------------------+
| sno | rollno | timein              |
+-----+--------+---------------------+
|   1 | st001  | 0000-00-00 00:00:00 |
|   2 | st002  | 0000-00-00 00:00:00 |
|   3 | st001  | 2012-07-11 12:05:23 |
+-----+--------+---------------------+
3 rows in set (0.00 sec)

答案 1 :(得分:2)

试试这个::

update 
student_log set timein=current_timestamp() 

where sno in

(

Select sno from 
(
select sno from  student_log where rollno='ST001' order by sno desc limit 1
) tmp
);