1

我开发了一个查询来清除除最近添加的行之外的所有行,基于存储为文本的字段 -> 时间戳和用户 ID 字段。

还涉及到不断变化的日期格式,因此也涉及到一些合并。

这是删除查询->

DELETE
FROM `table` main
WHERE COALESCE(STR_To_DATE( main.Timestamp , '%a %b %d %H:%i:%s CDT %Y' ), STR_To_DATE( main.Timestamp , '%a %b %d %H:%i:%s CST %Y' )) <
  (SELECT  MAX(COALESCE(STR_To_DATE( sub.Timestamp , '%a %b %d %H:%i:%s CDT %Y' ), STR_To_DATE( sub.Timestamp , '%a %b %d %H:%i:%s CST %Y' ))) 
  FROM `table` sub
  WHERE sub.Retrieving_User = main.Retrieving_User )

这不运行,抛出此错误->

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'main WHERE COALESCE(STR_To_DATE( main.Timestamp , '%a %b %d %H:%i:%s CDT %Y' ),' at line 2

我明白这是什么,只是不明白为什么会发生。如果我将查询更改为选择 ->

SELECT *
FROM `table` main
WHERE COALESCE(STR_To_DATE( main.Timestamp , '%a %b %d %H:%i:%s CDT %Y' ), STR_To_DATE( main.Timestamp , '%a %b %d %H:%i:%s CST %Y' )) <
  (SELECT  MAX(COALESCE(STR_To_DATE( sub.Timestamp , '%a %b %d %H:%i:%s CDT %Y' ), STR_To_DATE( sub.Timestamp , '%a %b %d %H:%i:%s CST %Y' ))) 
  FROM `table` sub
  WHERE sub.Retrieving_User = main.Retrieving_User )

它正确地抓取了我要删除的所有数据。

请告诉我,我不必更改查询的格式,因为我已经花了整个上午的时间。:(

编辑:

我通过研究发现,您无法从子查询中使用的同一个表中删除。所以我要为此创建一个很长的解决方法......稍后会更新......

4

1 回答 1

-1
DELETE from `table` where COALESCE(STR_To_DATE( Timestamp , '%a %b %d %H:%i:%s CDT %Y' ), STR_To_DATE( Timestamp , '%a %b %d %H:%i:%s CST %Y' )) in
(
SELECT COALESCE(STR_To_DATE( main.Timestamp , '%a %b %d %H:%i:%s CDT %Y' ), STR_To_DATE( main.Timestamp , '%a %b %d %H:%i:%s CST %Y' ))
FROM `table` main
WHERE COALESCE(STR_To_DATE( main.Timestamp , '%a %b %d %H:%i:%s CDT %Y' ), STR_To_DATE( main.Timestamp , '%a %b %d %H:%i:%s CST %Y' )) <
(SELECT  MAX(COALESCE(STR_To_DATE( sub.Timestamp , '%a %b %d %H:%i:%s CDT %Y' ), STR_To_DATE( sub.Timestamp , '%a %b %d %H:%i:%s CST %Y' ))) 
FROM `table` sub
WHERE sub.Retrieving_User = main.Retrieving_User)
)
于 2012-08-29T16:27:33.750 回答