mysql 批量drop_MySql批量drop table
今天發(fā)現(xiàn)數(shù)據(jù)庫中很多沒用的表,想清理掉。
發(fā)現(xiàn)mysql好像不支持類似這樣的寫法:drop table like "%r"
在oracle中,查了資料,是可以通過其他方式來實(shí)現(xiàn):看這里【我頂!鏈接丟了!】
那么想在mysql中實(shí)現(xiàn),怎么做呢?
兩個(gè)思路:
第一、修改mysql源碼,在drop的時(shí)候加上like關(guān)鍵字支持。
第二、寫一個(gè)腳本,在數(shù)據(jù)庫之外執(zhí)行。
-----------------------------《混個(gè)》-------------------------------
第一個(gè)方法,現(xiàn)在還沒有辦法去做到。【水平不夠=。=】
第二個(gè)方法的思路:
1、連接數(shù)據(jù)庫
2、查詢出所有的符合條件的表
3、挨個(gè)刪除【刪除過程遇到錯(cuò)誤輸出提示即可】
針對第二個(gè)方法的腳本如下:
先創(chuàng)建一些表:腳本如下
#! /bin/bash
for((i=1;i<=10;i++));
do
mysql -P3307 -uroot -proot -e"use test;create table tb_$i(id int);"
done;
然后創(chuàng)建刪除shell:
#! /bin/bash
word=`echo $1`
params=`echo $#`
echo "your input param is|"$word"|"
#param is ok?
if [ $params -lt 1 ]
then
echo "usage:drop 'yourword'"
exit
fi
#connect mysql and read tb names
var=$(mysql -P3307 -uroot -proot -e"use test;show tables like '$word';")
count=0
#read table names
for i in $var;
do
let count=$count+1
if [ $count -ne 1 -a $count -ne 2 ]
then
#delete from db
echo "deleting ...$i"
mysql -P3307 -uroot -proot -e"use test;drop table $i"
fi
done;
上面是drop腳本。使用方法:
drop ‘%a%’
需要在后面的參數(shù)中指明要匹配的內(nèi)容。與like關(guān)鍵字后面要加的內(nèi)容一樣。
腳本中每次執(zhí)行都需要連接數(shù)據(jù)庫。效率比較低下。但是對于少量的表,不會有太大區(qū)別。----------------------------------------------------------
if [ $count -ne 1 -a $count -ne 2 ]意思是說,不考慮第一個(gè)和第二個(gè)參數(shù)。因?yàn)閺膍ysql讀出來的表名稱是這樣的:;
Tables_in_test () tb_1 tb_10 tb_2 tb_3 tb_4 tb_5 tb_6 tb_7 tb_8 tb_9
前兩個(gè)需要忽略。
--------------------------------------------------------------
mysql -P3307 -uroot -proot -e"use test;show tables like '$word';"
mysql可以用-e參數(shù)來直接執(zhí)行命令。
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的mysql 批量drop_MySql批量drop table的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: function 多个函数用一个_一列转
- 下一篇: linux cmake编译源码,linu