MySQL dropping all indexes from table

后端 未结 4 719
小鲜肉
小鲜肉 2021-01-17 10:27

I have a MySQL database that runs for some time now with many changes on it. Lately I looked over it and I noticed that in some cases I have doubled the index on the same fi

相关标签:
4条回答
  • 2021-01-17 10:36

    In Ruby on Rails I do this:

    indexes = ActiveRecord::Base.connection.execute("SHOW INDEX FROM tablename")
    indexes.each do |index|
      ActiveRecord::Base.connection.execute("ALTER TABLE tablename DROP INDEX #{index[2]};")
    end
    
    0 讨论(0)
  • 2021-01-17 10:52

    no there isnt a command. you can however write a script that shows all databases, shows all tables inside thowe databases, shows all indexes inside those tables and drops them all. but i'n not gonna write that for you if you don't start accepting some answers. you can also use phpmyadmin or another graphical tool to select this neat "check all" box for every table.

    0 讨论(0)
  • 2021-01-17 10:53

    Simple script:

    -- list all non-unique indexes
    SELECT table_name AS `Table`,
           index_name AS `Index`,
           GROUP_CONCAT(column_name ORDER BY seq_in_index) AS `Columns`
    FROM information_schema.statistics
    WHERE NON_UNIQUE = 1 AND table_schema = 'mydatabase' AND table_name = 'mytable'
    GROUP BY 1,2;
    
    -- drop all non-unique indexes
    SET SESSION group_concat_max_len=10240;
    
    SELECT CONCAT('ALTER TABLE ', `Table`, ' DROP INDEX ', GROUP_CONCAT(`Index` SEPARATOR ', DROP INDEX '),';' )
    FROM (
    SELECT table_name AS `Table`,
           index_name AS `Index`
    FROM information_schema.statistics
    WHERE NON_UNIQUE = 1 AND table_schema = 'mydatabase' AND table_name = 'mytable'
    GROUP BY `Table`, `Index`) AS tmp
    GROUP BY `Table`;
    
    -- add all non-unique indexes , WITHOUT index length spec
    SET SESSION group_concat_max_len=10240;
    SELECT CONCAT('ALTER TABLE ', `Table`, ' ADD INDEX ', GROUP_CONCAT(CONCAT(`Index`, '(', `Columns`, ')') SEPARATOR ',\n ADD INDEX ') )
    FROM (
    SELECT table_name AS `Table`,
           index_name AS `Index`,
            GROUP_CONCAT(column_name ORDER BY seq_in_index) AS `Columns`
    FROM information_schema.statistics
    WHERE NON_UNIQUE = 1 AND table_schema = 'mydatabase' AND table_name = 'mytable'
    GROUP BY `Table`, `Index`) AS tmp
    GROUP BY `Table`;
    
    0 讨论(0)
  • 2021-01-17 10:58

    If you have phpmyadmin or any similar tool you can do that very easily graphically.

    Or for every index do something like

    ALTER TABLE  `table` DROP INDEX  `NameIndex`
    

    You can get the indexes with

    SHOW INDEX FROM `table`
    
    0 讨论(0)
提交回复
热议问题