如何更新ID = SELECT(...) - SQL的某些行

时间:2015-06-03 09:46:49

标签: mysql sql

我有一张桌子 - "记录"。

+-------+--------+-----------+---------------+
| logId | spName | startTime | executionTime |
+-------+--------+-----------+---------------+
|  1    | mail   | 11:54:49  |    300        |
|  2    | calc   | 13:12:11  |    500        |
| ....  |        |           |               |
|  100  | log    | 15:30:30  |    400        |
+-------+--------+-----------+---------------+

我想更新它:

UPDATE logs 
SET executionTime = 600
WHERE logId = ( SELECT max(logId) FROM logs WHERE spName = 'calc' )

但我收到错误:

  

错误代码:1093。您无法指定目标表'日志'用于FROM子句中的更新

我不知道如何修复它(

4 个答案:

答案 0 :(得分:2)

您可以使用ORDER By和LIMIT

通过单个查询执行此操作
UPDATE logs 
SET executionTime = 600
WHERE spName = 'calc'
ORDER By logId DESC
LIMIT 1

这将只更新一行logId

答案 1 :(得分:1)

试试这个:

UPDATE logs a,
(SELECT SELECT max(logId) max_logs FROM logs WHERE spName = 'calc') AS b
SET executionTime = 600
WHERE a.logId = b.max_logs

答案 2 :(得分:0)

您可以为此

使用加入更新
update logs l1
join (
 select max(logId) from logs WHERE spName = 'calc'
)l2 on l1.logId = l2.logId
set l1.executionTime = 600

答案 3 :(得分:-1)

UPDATE logs 
SET executionTime = 600
WHERE logId = ( SELECT logId FROM logs WHERE spName = 'calc' )