如何从表中删除除最新10行之外的所有行

时间:2013-05-28 17:07:06

标签: php mysql

我有一个结果为(str)的Mysql架构,创建了(timestamp, current on create)我希望运行一个查询来删除除最后10个之外的所有内容,我该怎么做?

4 个答案:

答案 0 :(得分:8)

  DELETE FROM tablename 
    WHERE id NOT IN (
      SELECT id FROM tablename 
      ORDER BY created DESC 
      LIMIT 10);

答案 1 :(得分:0)

你应该先收集10个ids

CREATE TEMPORARY TABLE ids_to_keep ENGINE=MyISAM
SELECT id FROM tablename WHERE 1=2;
INSERT INTO ids_to_keep
SELECT id FROM tablename ORDER BY created DESC LIMIT 10
ALTER TABLE ids_to_keep ADD PRIMARY KEYS (id);

从那里尝试以下两种技术之一:

技巧#1:删除加入

DELETE A.* FROM tablename A
LEFT JOIN ids_to_keep B USING (id)
WHERE B.id IS NULL;
DROP TABLE ids_to_keep;

技术#2:桌子休闲

CREATE TABLE tablename_new LIKE tablename;
ALTER TABLE tablename RENAME tablename_org;
INSERT INTO tablename_new
SELECT A.* FROM tablename_org A INNER JOIN ids_to_keep B USING (id);
DROP TABLE tablename_org;
ALTER TABLE tablename_new RENAME tablename;
DROP TABLE ids_to_keep;

试一试!!!

答案 2 :(得分:0)

您还可以使用方法的变体来使用自联接查找表中的第N个最大值。

DELETE FROM tablename WHERE created < (
SELECT created FROM tablename t1 WHERE
 (N - 1) = (SELECT COUNT( DISTINCT( created )
            FROM tablename t1
            WHERE t2.created > t1.created ) ) )

查询的内部部分为您提供表格中“已创建”的第N个最大值,您可以将其用作删除先前所有内容的参考。

答案 3 :(得分:0)

好的,这是9行,而不是10行,但你明白了......

SELECT * FROM created;
+---------------------+
| t                   |
+---------------------+
| 2013-05-28 19:17:03 |
| 2013-05-28 19:17:06 |
| 2013-05-28 19:17:09 |
| 2013-05-28 19:17:11 |
| 2013-05-28 19:17:13 |
| 2013-05-28 19:17:16 |
| 2013-05-28 19:17:17 |
| 2013-05-28 19:17:19 |
| 2013-05-28 19:17:21 |
| 2013-05-28 19:17:23 |
| 2013-05-28 19:17:25 |
| 2013-05-28 19:17:27 |
| 2013-05-28 19:17:29 |
| 2013-05-28 19:17:31 |
| 2013-05-28 19:17:33 |
| 2013-05-28 19:17:35 |
| 2013-05-28 19:17:37 |
| 2013-05-28 19:17:39 |
+---------------------+
18 rows in set (0.00 sec)

DELETE a
  FROM created a
  JOIN
     (  SELECT x.*
          FROM created x
          JOIN created y
            ON y.t >= x.t
         GROUP
            BY x.t
        HAVING COUNT(*) = 10
     ) b
    ON b.t >= a.t;

SELECT * FROM created;
+---------------------+
| t                   |
+---------------------+
| 2013-05-28 19:17:23 |
| 2013-05-28 19:17:25 |
| 2013-05-28 19:17:27 |
| 2013-05-28 19:17:29 |
| 2013-05-28 19:17:31 |
| 2013-05-28 19:17:33 |
| 2013-05-28 19:17:35 |
| 2013-05-28 19:17:37 |
| 2013-05-28 19:17:39 |
+---------------------+