我目前正在使用:
SELECT * FROM users ORDER BY date_time DESC LIMIT 0, 80
要显示最近的 80 个用户名,我如何进行查询以删除这 80 个之后的任何其他条目?
我想我需要一个 cron 作业,但它需要执行什么样的查询?
这里有不同的方法:
delete users from users
LEFT JOIN
(
select id from users order by date_time DESC LIMIT 0, 80) t1 ON users.id=t1.id
where t1.id is null
并且没有限制:
delete users from users
LEFT JOIN
(
select id from
(
SELECT id,
@curRow := @curRow + 1 AS row_number
FROM users,(SELECT @curRow := 0) r
ORDER BY date_time DESC) t where row_number<=80
) t1 ON users.id=t1.id
where t1.id is null
您需要使用子查询
DELETE FROM USERS where ID NOT IN
(SELECT ID FROM users ORDER BY date_time DESC LIMIT 0, 80)
因为删除时不能使用限制
尝试使用LEFT JOIN
.
DELETE a
FROM users a
LEFT JOIN
(
SELECT ID
FROM users
ORDER BY date_time DESC
LIMIT 0, 80
) b ON a.ID = b.ID
WHERE b.ID IS NULL
未经测试,但可能使用用户变量来分配序列号:-
DELETE users
FROM users
INNER JOIN
(
SELECT ID, @Sequence:=@Sequence + 1 AS aSequence
FROM (SELECT ID, date_time FROM users ORDER BY date_time) a
CROSS JOIN (SELECT @Sequence:=0) b
) c
ON users.ID = c.ID
AND c.aSequence > 80
使用中间子查询怎么样?只是一个想法。
DELETE FROM `users`
WHERE id NOT IN (
SELECT id
FROM (
SELECT id
FROM `users`
ORDER BY date_time DESC
LIMIT 80
) AS q
);