Group by user ID, retain the latest 1000 data records of the user, more than 1000 data records

Source: Internet
Author: User
Database field: id, user_id, date ,... other fields: MySQLBEGIN # Routinebodygoeshere... * If you query more than 1000 entries, delete the statement * DECLAREact_friends_user_idINT; DECLAREact_friends_min_idINT; DECLAREdnINTdefault0; * define the query statement * DECLAREactCURSOR

Database field: id, user_id, date ,... other fields: MySQL BEGIN # Routine body goes here... /* delete a query that contains more than 1000 entries */DECLARE act_friends_user_id INT; DECLARE act_friends_min_id INT; DECLARE dn INT default 0;/* define the query statement */DECLARE act CURSOR

Database field: id, user_id, date,... other fields MySQL
BEGIN # Routine body goes here... /* If you query more than 1000 entries, delete the statement */DECLARE act_friends_user_id INT; DECLARE act_friends_min_id INT; DECLARE dn INT default 0; /* define the query statement */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; /* Start the loop */OPEN act; act_loop: LOOPFETCH act INTO act_friends_user_id;/* jump out of the cursor loop when the condition is not found at the end of the loop */if dn = 1 THENLEAVE act_loop; END if;/* obtain the minimum ID value of the latest 1000 data records */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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.