该表包含列id
,timestamp
(例如2013-09-23 12:10:53),activity
,我想添加另一列{{1}这将包含每个活动的持续时间(即下一行时间戳和当前时间戳之间的差异)。
我已尝试过此查询:
duration
得到了这个错误:
UPDATE `MyTable` this SET `duration`=
(SELECT DATEDIFF(next.`timestamp`, curr.`timestamp`)
FROM `MyTable` curr
JOIN `MyTable` next
ON next.`id` = curr.`id`+1
WHERE this.`id` = curr.`id`)
我该怎么做呢?
答案 0 :(得分:1)
相反,请使用join
:
UPDATE MyTable this left join
MyTable next
ON next.id = this.id + 1
SET this.duration = DATEDIFF(next.timestamp, this.timestamp) ;
我认为错误是不言自明的。 MySQL中通常的解决方案是将update
转换为使用join
而不是相关的子查询。
答案 1 :(得分:0)
为您提供一些参考
You can't specify target table for update in FROM clause
http://dev.mysql.com/doc/refman/5.0/en/update.html
UPDATE `MyTable` this SET `duration`=
(SELECT DATEDIFF(next.`timestamp`, curr.`timestamp`)
FROM (SELECT * from MyTable) curr
JOIN (SELECT * from MyTable) next
ON next.`id` = curr.`id`+1
WHERE this.`id` = curr.`id`);