SQL 删除带有限制的 select 查询后的行
SQL delete rows after a select query with a limit
我想从包含多个用户的 table 中删除用户最近的 20 次测试以外的所有测试。
尝试 1:
DELETE FROM tests WHERE EXISTS (SELECT * FROM tests WHERE user_id = 38 ORDER BY test_timestamp DESC LIMIT 20, 100);
尝试 2:
DELETE FROM tests WHERE user_id = 38 ORDER BY test_timestamp DESC LIMIT 20, 100;
是否有任何更改可以使上述示例起作用,或者我是否需要使用 PHP 设置行计数变量来解决我的偏移问题?
对于尝试 1,这是正确的语法
delete from tests
where the primary key field in
(select the primary key field
etc
)
尝试:
DELETE FROM tests
WHERE tests.user_id = 38
and tests.ID in (SELECT id
FROM tests t
WHERE t.user_id = tests.user_id
ORDER BY test_timestamp DESC LIMIT 20, 100);
在 MySQL 中,您可以使用 join
:
DELETE t
FROM tests t JOIN
(SELECT tt.timestamp
FROM tests tt
WHERE t.user_id = 38
ORDER BY tt.timestamp DESC
OFFSET 19 LIMIT 1
) tt
ON t.user_id = tt.user_id and t.timestamp < tt.timestamp;
MySQL不支持另外两个"obvious"方法。
- MySQL 不支持
DELETE
的 LIMIT
子句中的 OFFSET
。
- MySQL 不支持正在修改的 table 的
WHERE
子句中的操作(不向查询添加额外的复杂性)。
我想从包含多个用户的 table 中删除用户最近的 20 次测试以外的所有测试。
尝试 1:
DELETE FROM tests WHERE EXISTS (SELECT * FROM tests WHERE user_id = 38 ORDER BY test_timestamp DESC LIMIT 20, 100);
尝试 2:
DELETE FROM tests WHERE user_id = 38 ORDER BY test_timestamp DESC LIMIT 20, 100;
是否有任何更改可以使上述示例起作用,或者我是否需要使用 PHP 设置行计数变量来解决我的偏移问题?
对于尝试 1,这是正确的语法
delete from tests
where the primary key field in
(select the primary key field
etc
)
尝试:
DELETE FROM tests
WHERE tests.user_id = 38
and tests.ID in (SELECT id
FROM tests t
WHERE t.user_id = tests.user_id
ORDER BY test_timestamp DESC LIMIT 20, 100);
在 MySQL 中,您可以使用 join
:
DELETE t
FROM tests t JOIN
(SELECT tt.timestamp
FROM tests tt
WHERE t.user_id = 38
ORDER BY tt.timestamp DESC
OFFSET 19 LIMIT 1
) tt
ON t.user_id = tt.user_id and t.timestamp < tt.timestamp;
MySQL不支持另外两个"obvious"方法。
- MySQL 不支持
DELETE
的LIMIT
子句中的OFFSET
。 - MySQL 不支持正在修改的 table 的
WHERE
子句中的操作(不向查询添加额外的复杂性)。