SELECT SUM(PresentSum) FROM `Lg_ConsumeDetail0` WHERE ConsumeDate < '2016-11-01' AND OpId != 300;
+
SELECT SUM(PresentSum) FROM `Lg_ConsumeDetail1` WHERE ConsumeDate < '2016-11-01' AND OpId != 300;
每次返回的是+号上下两句sql查询的和。
注意,有可能其中一句sql返回的是NULL或者报错信息(没有这个表)。
格试如下:
输出结果
数据库名1 sql1+sql2的和
数据库名2 sql1+sql2的和
数据库名3 sql1+sql2的和
... ...
中间要以tab健隔开
代码如下:
#!/bin/bash
USER='root'
PASSWD='123456'
IP='192.168.1.1'
for i in tzpay tzpay360 tzpay_179 tzpay_9377 tzpay_dx2 tzpay_dx3 tzpay_dx4 tzpay_dx5 tzpay_dx6 tzpay_lt1 tzpay_lt2 tzpay_lt3 tzpay_lt4 tzpay_yy
do
table1=$(mysql -u$USER -p$PASSWD -h$IP $i -e "SELECT SUM(BasicSum) FROM Lg_ConsumeDetail0 WHERE ConsumeDate < '2016-11-01' AND OpId = 300;" | tail -1 | awk '{print $1}')
table4=$(mysql -u$USER -p$PASSWD -h$IP $i -e 'show tables like "Lg_ConsumeDetail0"' | wc -l)
#判断存不存在表0,不存在则打印表1的值,跳过本次循环
if [ $table4 -eq 0 ];then
mysql -u$USER -p$PASSWD -h$IP $i -e "SELECT SUM(BasicSum) FROM Lg_ConsumeDetail1 WHERE ConsumeDate < '2016-11-01' AND OpId = 300;" | tail -1 | awk '{print b"\t"$1}'
continue
fi
table2=$(mysql -u$USER -p$PASSWD -h$IP $i -e 'show tables like "Lg_ConsumeDetail1"' | wc -l)
#判断存不存在表1,不存在则打印表0的值,跳过本次循环
if [ $table2 -eq 0 ];then
mysql -u$USER -p$PASSWD -h$IP $i -e "SELECT SUM(BasicSum) FROM Lg_ConsumeDetail0 WHERE ConsumeDate < '2016-11-01' AND OpId = 300;" | tail -1 | awk -vb=$i '{print b"\t"$1}'
continue
fi
table3=$(mysql -u$USER -p$PASSWD -h$IP $i -e "SELECT SUM(BasicSum) FROM Lg_ConsumeDetail1 WHERE ConsumeDate < '2016-11-01' AND OpId = 300;" | tail -1 | awk '{print $1}')
#判断表1和表0同时为NULL的话,则直接输出NULL,跳过本次循环
if [ $table3 == "NULL" ] && [ $table1 == "NULL" ];then
echo NULL | awk -vb=$i '{print b"\t"$1}'
continue
fi
#判断表1为NULL的话,则直接输出表0的值,跳过本次循环
if [ $table3 == "NULL" ];then
mysql -u$USER -p$PASSWD -h$IP $i -e "SELECT SUM(BasicSum) FROM Lg_ConsumeDetail0 WHERE ConsumeDate < '2016-11-01' AND OpId = 300;" | tail -1 | awk -vb=$i '{print b"\t"$1}'
continue
fi
#判断表0为NULL的话,则直接输出表1的值,跳过本次循环
if [ $table1 == "NULL" ];then
mysql -u$USER -p$PASSWD -h$IP $i -e "SELECT SUM(BasicSum) FROM Lg_ConsumeDetail1 WHERE ConsumeDate < '2016-11-01' AND OpId = 300;" | tail -1 | awk '{print b"\t"$1}'
continue
fi
#上面判断都不存的话,就把表0和表1的值相加输出
expr $table1 + $table3 | awk -vb=$i '{print b"\t"$1}'
done
执行结果如下:
[root@10-9-181-186 opt]# sh sql_sum.sh
tzpay 69768460
tzpay360 23185990
tzpay_179 1259110
tzpay_9377 57750
tzpay_dx2 32938190
tzpay_dx3 33270350
tzpay_dx4 12540690
tzpay_dx5 13220880
tzpay_dx6 NULL
tzpay_lt1 33962100
tzpay_lt2 23586690
tzpay_lt3 10345880
tzpay_lt4 NULL
tzpay_yy NULL