我在字段timestamp
中设置了一个包含许多错误条目的数据库(设置为0000-00-00 00:00:00
,我想要做的是使用上一个有效时间戳更新此字段。我尝试过遗憾的是,这个查询没有成功(语法不被接受):
UPDATE `scontrini` s1
SET s1.`timestamp` =
(SELECT TOP 1 s2.`timestamp`
FROM `scontrini` s2
WHERE s2.`timestamp` <> '0000-00-00 00:00:00' AND s2.`id` < s1.`id`
ORDER BY s2.`id` DESC)
WHERE `scontrini`.`timestamp`= '0000-00-00 00:00:00';
有些解决方案建议使用inner join
,但我没有测试某些值的相等性。
提前致谢。
修改
我按照建议将查询更改为:
UPDATE `scontrini` as s1
SET s1.`timestamp` =
(SELECT s2.`timestamp`
FROM `scontrini` as s2
WHERE s2.`timestamp` <> '0000-00-00 00:00:00' AND s2.`id` < s1.`id`
ORDER BY s2.`id` DESC LIMIT 1)
WHERE s1.`timestamp`= '0000-00-00 00:00:00';
但我仍然收到错误消息。
静态分析:
1.在SELECT
附近:找到了一个新的陈述,但是这个陈述和前一个陈述之间没有分隔符。
2.接近第二WHERE
:这种类型的条款已经过检验
3.接近第二WHERE
:声明未被识别。
MySQL错误消息:
#1093 - Table 's1' is specified twice, both as a target for 'UPDATE' and as a separate source for data
谢谢。
答案 0 :(得分:0)
TOP用于SQL服务器而不是MySQL。在子查询的末尾使用LIMIT
来限制返回的行数。
UPDATE `scontrini` s1
SET s1.`timestamp` =
(SELECT s2.`timestamp`
FROM `scontrini` s2
WHERE s2.`timestamp` <> '0000-00-00 00:00:00' AND s2.`id` < s1.`id`
ORDER BY s2.`id` DESC LIMIT 1)
WHERE `scontrini`.`timestamp`= '0000-00-00 00:00:00';
答案 1 :(得分:0)
使用max()和正确的日期格式
UPDATE `scontrini` s1
SET s1.`timestamp` =
(
SELECT max(s2.`timestamp`)
FROM `scontrini` s2
WHERE DATE_FORMAT(s2`timestamp`, '%Y-%m-%d %h:%i:%s') <>
'0000-00-00 00:00:00' AND s2.`id`< s1.`id`
)
WHERE DATE_FORMAT(s1.`timestamp`, '%Y-%m-%d %h:%i:%s')= '0000-00-00 00:00:00';
答案 2 :(得分:0)
尝试
UPDATE `scontrini` as s1
SET s1.`timestamp` =
(SELECT s2.`timestamp`
FROM `scontrini` s2
WHERE s2.`timestamp` <> '0000-00-00 00:00:00' AND s2.`id` < s1.`id`
ORDER BY s2.`timestamp` DESC limit 0,1)
WHERE `s1`.`timestamp`= '0000-00-00 00:00:00';