在SQL数据库中只保留前50条记录并删除其余记录

时间:2014-01-21 10:34:31

标签: mysql sql-delete

我有一个分数表,由2个字段组成: name high score 。像这样:

----------------------- 
| name     | score    |
-----------------------
| John     | 2450     |
-----------------------
| Alice    | 2420     |
-----------------------
                         ... etc    

我需要删除所有行,直到排名前50位。

是否可以不创建另一个临时表?

3 个答案:

答案 0 :(得分:4)

请试试这个

delete from scores_tbl Where
id not in
(select * from
(select id from scores_tbl order by score desc limit 50)
 as temp)

答案 1 :(得分:2)

创建自动增量字段

alter table scores add id int unique auto_increment not null;

这将按照无条件的选择查询或按订单

的顺序自动为您的行编号
select * scores;
delete from scores where id > 50;

最后,删除该字段

alter table scores drop id;

答案 2 :(得分:0)

您需要一个唯一的字段,因此要么在删除之前和之后更改表格。

喜欢: alter table scores add id int unique auto_increment not null;

从ID>分数中删除50;

alter table drop column id;