2011-08-29 71 views
1

我如何能在表中刪除所有行recentposts如何刪除所有行除了50最新

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

你是指最新的5個或最新的50個? – gbn

回答

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) 
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和上)在早期版本這些都是MySQL的限制。

  • 您無法在同一查詢中從給定表中刪除和選擇。
  • MySQL在子查詢中不支持LIMIT。

所以對於以前的版本u能想出是爲此在兩個階段:

第一步

SELECT id FROM mytable ORDER BY id DESC LIMIT n; 

收集ID和使它們成爲一個逗號分隔的字符串:

DELETE FROM mytable WHERE id NOT IN (...comma-separated string...);