MySQL删除未选中的所有记录

时间:2013-08-29 12:50:22

标签: mysql sql-delete sql-subselect

我正在尝试根据时间戳删除除最近25个以外的所有条目。我试过这个:

DELETE FROM `chat` WHERE `IndexNo` NOT IN(SELECT `IndexNo` FROM `chat` ORDER BY `Timestamp` DESC LIMIT 25)

这会产生此错误:

#1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:1)

您不能依赖LIMIT子查询中的IN/ALL/ANY/SOME,而是可以使用多删除语法:

DELETE 
  `chat` 
FROM 
  `chat` 
    LEFT JOIN (SELECT `IndexNo` FROM `chat` ORDER BY `Timestamp` DESC LIMIT 25) AS `selected`
      ON `chat`.`IndexNo`=`selected`.`IndexNo` 
WHERE 
  `selected`.`IndexNo` IS NULL;

- 根据manual,这将在MySQL 5.0

之后起作用

答案 1 :(得分:0)

我猜这是一个关于子查询的更普遍的问题。试着看看这里:Problem with LIMIT & IN/ALL/ANY/SOME subquery