如何通过cron或ssh tty命令行执行的脚本按日期修剪多个mysql表?

时间:2016-12-07 09:23:10

标签: mysql bash cron

我试图弄清楚如何编写一个类似于我可以通过cron执行的@ https://dba.stackexchange.com/questions/20240/running-sql-query-on-all-databases的bash脚本。我个人打算在运行CentOS 6.8和Ubuntu 14.4及更高版本的mysql服务器上执行此脚本。

我有一个数据库“DB123”,有两个表“tbl001”和“tbl002”。 (DB和表名称是通用构造。)

在tbl001中,有一列“tbl001date”(类型为datetime“),其单元格值如”2015-10-26 16:14:45“。

在tbl002中,有一列“tbl002time”(类型为datetime“),其单元格值如”2015-10-26 16:14:45“。

我想出了如何通过phpMyAdmin手动查询以删除早于“给定时间”的所有行:

DELETE FROM `tbl001` WHERE `tbl001date` <= '2016-09-01 00:00:00'
DELETE FROM `tbl002` WHERE `tbl002time` <= '2016-11-01 00:00:00'

我要做的是让脚本在tbl001中删除超过90天的行,在tbl002中删除超过30天的行,依此类推......就像上面提到的脚本一样,我认为声明变量将是一个明智的选择。

类似的东西:

#!/bin/bash
# mysql credential 
user="root"
pass="root" 

# database name
database="DB123"

# list tables, columns, days to keep A thru Z
tableA="tbl001"
columnA="tbl001date"
daysA="90"
tableB="tbl002"
columnB="tbl002time"
daysB="30"
#And so on....

#Script Section 1:  Scripting to display a formatted table of worh about to be done the executes when script is ran from TTY command line but NOT when ran via cron...
#Example of what I envision for screen output when ran TTY command line...

If connection to mysql fails, notify user and quit. ie "Sorry, was unable to connect mysql server."  OR

If mysql credentials are invalid, notify user and quit. ie "The user/password combo declared are invalid, please verify your credentials and try again." OR

If a defined table or column does not exist, notify the user and quit. ie "$tableC, $tableD, and $tablesE do(es) not exist in $database, please verify the variables declared in this script." OR

The following tables will have rows older than "DATE" deleted...
TABLE          |DATE    
------------------------------------
echo "$tableA"  | (90 days before Today's Date)
echo "$tableB"  | (30 days before Today's Date)
echo "$tableC"  | (X days before Today's Date)
And so on...
Then output the following and wait for a response from user:

Is the above correct? (Type YES to continue/any this else to quit)

#Script Section 2:  Additional scripting to delete rows goes here...

#Script Section 3:  Additional scripting to compact the database after deleting rows to remove "overhead"

#Script Section 4:  Additional scripting to output results without regard to cron or tty execution

The mysql database, $database, on server $dnsdomainname had the following table rows deleted:
$tablaA had $number-of-rows deleted and was reduced/compacted from 200MB to 35MB in size
$tableB had $number-of-rows deleted and was reduced/compacted from 500MB to 75MB in size
And so on...  

我不承诺使用BASH脚本。如果使用Perl或其他语言更有意义,我完全乐于接受这个想法。

非常感谢任何帮助或指导。感谢您抽出宝贵时间阅读本文。

0 个答案:

没有答案
相关问题