我有这张桌子:
`id` `activity_time`
1 0000-00-00 00:00:00
2 2015-06-1 12:12:12
3 0000-00-00 00:00:00
4 0000-00-00 00:00:00
5 2015-06-2 13:13:13
我想用日期“0000-00-00 00:00:00”更新每一行,并将其设置为第一个下一个非“0000-00-00 00:00:00”行。
所以ID#1将设置为2015-06-1 12:12:12
。
和#3,#4将设置为2015-06-2 13:13:13
。
我正在尝试运行此查询:
UPDATE
table1
SET activity_time =
(
SELECT activity_time FROM table1 as t2
where
t2.activity_time != '0000-00-00 00:00:00'
AND
t2.id > table1.id
ORDER BY Id ASC
limit 1
)
WHERE activity_time = '0000-00-00 00:00:00'
但是我犯了这个错误:
You can't specify target table 'table1' for update in FROM clause.
答案 0 :(得分:2)
在MySQL中,您可以使用join
:
UPDATE table1 t1 JOIN
(SELECT t1.*,
(SELECT t1b.activity_time
FROM table1 t1b
WHERE t1b.activity_time <> '0000-00-00 00:00:00' AND
t1b.id > t1.id
ORDER BY t1b.id ASC
LIMIT 1
) as next_activity_time
FROM table1 t1a
WHERE t1a.activity_time <> '0000-00-00 00:00:00'
) tnxt
ON tnxt.id = t1.id
SET t1.activity_time = tnxt.next_activity_time
WHERE t1.activity_time = '0000-00-00 00:00:00';
基本思路是将您的查询重写为SELECT
以获取所需的值。然后join
返回查询以获取更新信息。