我有一个名为tbl_tmp_trans的表,它包含曾经做过的每个用户事务(现在最多6Mil!)
我们决定在我们的数据库中仅保留每个用户的最后100个事务,因此我们可以保持数据库干净,这是我提出的查询
delete from tbl_tmp_trans
where trans_id in
(
select trans_id
from
(
select trans_id
from tbl_faucets_transactions
order by date
group by user_id
limit 100
) foo
)
我究竟做错了什么?
因为这样做后,我的cpu达到了100%,mysql崩溃了。
在此先感谢PS:我们的数据库是Mysql,表引擎是Innodb
P.S2:我们大约有12万,而转换表有将近600万条记录
我有个建议...希望能对您有所帮助。
修改表格:
alter table tbl_tmp_trans add column todel tinyint(1);
实现一个存储过程,以使用游标遍历表并标记(设置todel
为1
)应删除的记录。为此的示例过程:
delimiter //
drop procedure if exists mark_old_transactions //
create procedure mark_old_transactions()
begin
declare done int default false;
declare tid int;
declare uid int;
declare last_uid int default 0;
declare count int default 0;
declare cur cursor for select trans_id, user_id from tbl_tmp_trans order by user_id, date desc;
declare continue handler for not found set done = true;
open cur;
repeat
fetch cur into tid, uid;
if (!done) then
if (uid!=last_uid) then
set count = 0;
end if;
set last_uid = uid;
set count = count + 1;
if (count > 100) then
update tbl_tmp_trans set todel=1 where trans_id=tid;
end if;
end if;
until done
end repeat;
close cur;
end //
调用该过程,也许做一些简单的检查(从表中删除多少个事务,等等),然后删除标记的记录。
call mark_old_transactions;
-- select count(*) from tbl_tmp_trans where todel=1;
-- select count(*) from tbl_tmp_trans;
delete from tbl_tmp_trans where todel=1;
最后,删除我们刚刚添加的列。
alter table tbl_tmp_trans drop column todel;
一些注意事项:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句