Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

sql - Delete data from all tables in MYSQL

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 possible?

I want to keep the database and tables.

question from:https://stackoverflow.com/questions/1885101/delete-data-from-all-tables-in-mysql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...