我如何删除表recentposts
DELETE FROM recentposts WHERE recentposts.`userId` = 12 AND recentposts.`Id`
NOT IN (SELECT * FROM recentposts WHERE `userId` = 12 ORDER BY viewdate LIMIT 50)
我尝试了许多类似于此的但他们没有奏效。谁能告诉我如何在Mysql中做到这一点。
答案 0 :(得分:3)
这个怎么样?
DELETE FROM recentposts
WHERE
recentposts.`userId` = 12
AND
recentposts.`Id` NOT IN (SELECT Id
FROM recentposts
WHERE `userId` = 12
ORDER BY viewdate DESC LIMIT 50)
答案 1 :(得分:2)
DELETE FROM `recentpost`
WHERE WHERE userId = 12 AND id NOT IN (
SELECT id
FROM (
SELECT id
FROM `table`
ORDER BY id DESC
LIMIT 50
) foo
);
PS:仅在早期版本中工作(MySQL 5.0.67及更高版本)AS这些是MySQL的限制。
所以对于以前的版本,你可以想出的是分两个阶段来完成:
第一步
SELECT id FROM mytable ORDER BY id DESC LIMIT n;
收集id并将它们组成逗号分隔的字符串:
DELETE FROM mytable WHERE id NOT IN ( ...comma-separated string... );