2012-07-11 67 views
2

我有一個表student_log,並且單個'rollno'有多個記錄。在MySQL中更新特定ID的最後一個條目

'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與update語句,該語句不工作。

我知道語法是正確的,但我認爲這只是意味着MySQL不允許更新使用子查詢。謝謝。詢問我是否遺漏了任何信息。

回答

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

編輯
測試我的查詢,並且是它的更多鈔票,或者我是怎麼在OP的表結構錯過

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) 
+0

這個作品!謝謝。 – 2012-07-11 10:07:14

+0

這是編寫查詢的好方法。我的意思是把查詢的不同部分放在不同的行上。使其更具可讀性。 – 2012-07-11 10:09:56

+2

@QuikTester如果你使用的查詢長度超過4096個字符,那麼你有一些訓練,你可以在哪裏進行排序:-) – 2012-07-11 10:13:44

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 
); 
+0

Sashi Kant,這也適用。但Puggan的更簡單。謝謝。 – 2012-07-11 10:11:47

相關問題