我有一个 Mysql 架构(str)
,已创建(timestamp, current on create)
,我想运行一个查询以删除除最后 10 个之外的所有内容,我该怎么做?
问问题
239 次
4 回答
8
DELETE FROM tablename
WHERE id NOT IN (
SELECT id FROM tablename
ORDER BY created DESC
LIMIT 10);
于 2013-05-28T17:08:59.553 回答
0
你应该先收集 10 个 id
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;
试试看 !!!
于 2013-05-28T17:49:09.683 回答
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 ) ) )
查询的内部部分为您提供了表中“created”的第 N 个最大值,您可以将其用作删除之前所有内容的参考。
于 2013-05-28T18:00:07.700 回答
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 |
+---------------------+
于 2013-05-28T18:17:34.413 回答