使用Bash脚本进行数据库归档

时间:2015-02-18 06:47:38

标签: mysql database bash

我有一个名为 vitalstatistix的MySQL 5.5交易数据库我希望每月存档。该数据库由一个名为 asterisk_event 的大表和较小的查找表组成。

asterisk_event表有一个名为 datetime 的列。

1.我想提取该列的year_month部分:

SELECT DISTINCT EXTRACT(YEAR_MONTH FROM datetime) AS DATEPART  
FROM asterisk_event 
WHERE `datetime` <=  NOW() - INTERVAL 6 MONTH


+----------+
| DATEPART |
+----------+
|   201307 |
|   201308 |
|   201309 |
|   201310 |
|   201311 |
|   201312 |
|   201401 |
|   201402 |
|   201403 |
|   201404 |
|   201405 |
|   201406 |
|   201407 |
|   201408 |
+----------+
20 rows in set (1.31 sec)
  1. 并且,对于上面返回的每个DATEPART,创建一个名为 vitalstatistix _&#39; datepart&#39; 的数据库,例如vitalstatistix_201307
  2. 每个创建的存档数据库都将包含一个月的数据。

    我需要创建一个bash脚本和/或一个SQL(MySQL)存储过程或语句来补充它。

    这就是我现在所拥有的:

    #!/bin/bash
    MUSER="root"
    MPASS="password"
    MHOST="localhost"
    MYSQL="$(which mysql)"
    MYSQLDUMP="$(which mysqldump)"
    
    
    DB="vitalstatistix"
    for db in ${DB}
    do
    
    # Step 2: Identify the months that need archiving
     echo "$MYSQL -u$MUSER  $db -Bse 'SELECTING .... FROM asterisk_event'"
    DATEPARTS="$($MYSQL -u$MUSER -p$MPASS $db -Bse 'SELECT DISTINCT EXTRACT(YEAR_MONTH FROM datetime) AS DATEPART  FROM asterisk_event WHERE `datetime` <=  NOW() - INTERVAL 6 MONTH')"
    echo "[START ARCHIVING]"
    echo "Database: "$db
    echo ${DATEPARTS}
    
    
    # Step 3: Create archive databases
    
       for DATEPART in ${DATEPARTS}
        do
         echo $DATEPART
        #ENTER LINES OF CODE HERE
        done
     echo "[END ARCHIVING]"
    done
    

1 个答案:

答案 0 :(得分:0)

像这样......

MYSQL="mysql -uuser -ppassword database -BNe"

$MYSQL "SELECT DISTINCT EXTRACT(YEAR_MONTH FROM datetime) AS DATEPART
     FROM asterisk_event WHERE `datetime` <=  NOW() - INTERVAL 6 MONTH"
   | while read date; do
        $MYSQL "CREATE TABLE vitalstatistix_$date SELECT * FROM asterisk_event 
                  WHERE datetime LIKE '$date%'"
   done

更容易的事情是在插入时使用mysql trigger,将数据插入第二个表和每月的每个开头,将此表重命名为vitalstatistix_<date>并重新开始。