Maison > Article > base de données > 按照用户ID进行分组,保留用户的最新的1000条数据,超过1000条的都
数据库字段:id,user_id,date,...其他若干字段 MySQL BEGIN#Routine body goes here.../*查询用户超过1000条则进行删除功能 */DECLARE act_friends_user_id INT;DECLARE act_friends_min_id INT;DECLARE dn INT default 0;/*定义查询语句*/DECLARE act CURSOR
数据库字段:id,user_id,date,...其他若干字段 MySQLBEGIN #Routine body goes here... /* 查询用户超过1000条则进行删除功能 */ DECLARE act_friends_user_id INT; DECLARE act_friends_min_id INT; DECLARE dn INT default 0; /*定义查询语句*/ DECLARE act CURSOR FOR SELECT user_id FROM act_friends GROUP BY user_id HAVING COUNT(user_id) > 1000; DECLARE EXIT HANDLER FOR NOT FOUND set dn=1; /*开始进行循环*/ OPEN act; act_loop:LOOP FETCH act INTO act_friends_user_id; /*循环到最后查找不到条件则跳出这个游标循环*/ if dn=1 THEN LEAVE act_loop; END if; /*获取最新1000条数据中的最小ID值*/ select min(id) into act_friends_min_id from (select id from act_friends where user_id =act_friends_user_id ORDER BY date DESC limit 1000) as temp; SELECT act_friends_min_id; DELETE FROM act_friends where user_id = act_friends_user_id AND id < act_friends_min_id; END LOOP; CLOSE act; END