MYSQL delete all results having count(*)=1

后端 未结 3 543
天命终不由人
天命终不由人 2020-12-15 01:19

I have a table taged with two fields sesskey (varchar32 , index) and products (int11), now I have to delete all rows that having group by sesskey count(*) = 1. I\'m trying a

3条回答
  •  眼角桃花
    2020-12-15 01:59

    Or if you're using an older (pre 4.1) version of MySQL and don't have access to subqueries you need to select your data into a table, then join that table with the original:

    CREATE TABLE delete_me_table (sesskey varchar32, cur_total int);
    
    INSERT INTO delete_me_table SELECT sesskey, count(*) as cur_total FROM orig_table
    WHERE cur_total = 1 GROUP BY sesskey;
    
    DELETE FROM orig_table INNER JOIN delete_me_table USING (sesskey);
    

    Now you have a table left over named delete_me_table which contains a history of all the rows you deleted. You can use this for archiving, trending, other fun and unusual things to surprise yourself with.

提交回复
热议问题