MySQL Backup – How to Exclude Tables by Name Prefix in mysqldump

backupMySQLmysqldump

I'd like to exclude a group of tables from a mysqldump command (from a bash script). I might not know the exact table names ahead of time but they will be named with the prefix foo_ or might contain another known suffix like _BAK_[%Y%m%d]

Best Answer

This is based on answers from How do you mysqldump specific table(s)?

To exclude all tables from a mysqldump that starts with foo_, here is the shell script to do it

MYSQL_DATA=mydb
MYSQL_USER=root
MYSQL_PASS=rootpassword
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
SQL="SET group_concat_max_len = 102400;"
SQL="${SQL} SELECT GROUP_CONCAT(CONCAT('--ignore-table=',table_name) SEPARATOR ' ')"
SQL="${SQL} FROM information_schema.tables WHERE table_schema='${MYSQL_DATA}'"
SQL="${SQL} AND table_name LIKE 'foo_%'"
EXCLUSION_LIST=`mysql ${MYSQL_CONN} -AN -e"${SQL}"`
mysqldump ${MYSQL_CONN} ${MYSQL_DATA} ${EXCLUSION_LIST} > ${MYSQL_DATA}_tables.sql

To exclude all tables from a mysqldump that starts with foo_, adjust this line

SQL="${SQL} AND table_name LIKE 'foo_%'"

to whatever pattern you need. Maybe you can use the REGEXP operator

SQL="${SQL} AND table_name REGEXP '\_BAK\_2[0-9][0-9][0-9][0-9][0-9][0-9][0-9]"

Give it a Try !!!