Delete data from all tables in MYSQL

前端 未结 16 1787
自闭症患者
自闭症患者 2020-12-13 09:17

I have 100 tables, 40,000 rows in each table. I want to go into MySQL and delete all rows from all tables.

...in 1 statement, if p

16条回答
  •  没有蜡笔的小新
    2020-12-13 10:01

    I don't think so (but I've been wrong before). What I tend to do is those cases is a two-step process.

    If your DBMS has a command line interface, you can use it to create a script to do the bulk of the work, something like:

    db2 "select 'db2 delete from ' | tblname from sysibm.systables
        where owner = 'pax'" >p2.sh
    p2.sh
    

    The first bit simply creates a p2.sh file (or a p2.cmd file under Windows) containing a delete from statement for every table owned by pax. Then you just run that command file to do the dirty work. You may want to check it first, of course :-)

    Not the one-step process you were looking for but still very simple. I'm assuming here that mysql also has a command line interface.

    Update:

    The MySQL version of the above looks like it should be:

    echo "select 'mysql truncate table ' | table_name
                  from information_schema.tables" | mysql >p2.sh
    bash p2.sh
    

    This uses the truncate command which is usually more efficient than delete from for deleting all rows. It also uses the proper MySQL system tables to get the table names.

    One point though - you may want to put a where clause on that select to limit the tables to those you want deleted. The query as it stands will try to delete every table. One possibility is to limit it with specific table_schema and/or table_type values.

提交回复
热议问题