将新数据插入表后清理旧数据

时间:2012-07-05 11:54:19

标签: mysql sql

首先我们从空表开始

rows = 0

其次我们插入随机行,比方说3400

rows = 3400

我第三次计算表中有多少行,然后插入新行,然后从计数中删除行< =。

此逻辑仅适用于第一次。如果重复计数将始终为3400,但id将增加,因此不会删除行

我无法使用最后插入的ID,因为行是随机的,我不会加载多少。

//更新

"SELECT count(*) from table" - the total count so far
"INSERT INTO tab_videos_watched (id , name) values (id , name)" - this is random can     be 3400 or 5060 or 1200
"DELETE FROM table  WHERE idtable  <= $table_count"

1 个答案:

答案 0 :(得分:0)

如果id自动递增,那么你应该使用:

select max(id) from my_table;

将此maxId读入变量,然后在发出delete查询时使用,如:

delete from my_table where id <= ?;

将查询参数替换为最后找到的maxId值。

或者,您可以将列last_inserted定义为datetime类型 在下次插入之前,将其选择为局部变量。

select max(last_inserted) as 'last_inserted' from my_table;

插入完成后,使用last_inserted删除记录。

delete from my_table where last_inserted <= ?;

将查询参数替换为最后找到的last_inserted值。