Delete, Truncate or Drop to clean out a table in MySQL

前端 未结 6 560
野性不改
野性不改 2021-02-07 03:49

I am attempting to clean out a table but not get rid of the actual structure of the table. I have an id column that is auto-incrementing; I don\'t need to keep the

6条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 04:20

    Another possibility involves creating an empty copy of the table, setting the AUTO_INCREMENT (with some eventual leeway for insertions during the non-atomic operation) and then rotating both :

    CREATE TABLE t2_new LIKE t2;
    
    SELECT @newautoinc:=auto_increment /*+[leeway]*/ 
      FROM information_schema.tables
     WHERE table_name='t2';
    
    SET @query = CONCAT("ALTER TABLE t2_new AUTO_INCREMENT = ", @newautoinc);
    PREPARE stmt FROM @query;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    RENAME TABLE t2 TO t2_old, t2_new TO t2;
    

    And then, you have the extra advantage of being still able to change your mind before removing the old table.

    If you reconsider your decision, you can still bring back old records from the table before the operation:

    INSERT /*IGNORE*/ INTO t2 SELECT * FROM t2_old /*WHERE [condition]*/;
    

    When you're good you can drop the old table:

    DROP TABLE t2_old;
    

提交回复
热议问题