0

http://sqlfiddle.com/#!2/d21f3/1

I have a table with some entries here, I want to keep only 50 messages in this table sorted by message_id, and DELETE the rest of entries.

Please help me with the query.

Thanks in advance.

4

2 回答 2

1

试试我用过ORDER BY message_id DESC的这个,随心所欲地改变它,它将删除除已选择的 50 个条目之外的所有条目,我为查询设置了别名,因为您不能使用同一个表来选择删除操作

DELETE FROM `chat_history` WHERE id NOT IN ( SELECT t.id FROM 
(SELECT id FROM chat_history ORDER BY message_id DESC LIMIT 50 ) t)
于 2013-11-07T14:35:47.407 回答
1

例如。

DELETE a 
  FROM chat_history a 
  LEFT 
  JOIN 
     ( SELECT x.message_id 
         FROM chat_history x 
         JOIN chat_history y 
           ON y.message_id >= x.message_id 
        GROUP 
           BY x.message_id 
       HAVING COUNT(*) <= 50
     ) b 
    ON b.message_id = a.message_id 
 WHERE b.message_id IS NULL;

http://sqlfiddle.com/#!2/361b4/1

于 2013-11-07T14:41:30.647 回答