mysql - 如何使用 if -else 基于条件通过 shell 脚本执行 MySQL 命令?
问题描述
我正在使用此代码为自动化目的获取我想要的输出,但总是面临与 if 条件相关的错误......
mysql --login-path=local << EOF >/home/test.sql
use testdb;
if ([$(date +%m) -eq 1] | [$(date +%m) -eq 3] | [$(date +%m) -eq 5] | [$(date +%m) -eq 7] | [$(date +%m) -eq 8] | [$(date +%m) -eq 10] | [$(date +%m) -eq 12])
then
select COUNT(id) from xxx where app_id ='ABC' and date(creation_date) between '$(date +%F -d "tomorrow -31 days")' and '$(date +%F)' and action='AUTH' ;
elseif [$(date +%m) -eq 2 ]
then
select COUNT(id) from xxx where app_id ='ABC' and date(creation_date) between '$(date +%F -d "tomorrow -28 days")' and '$(date +%F)' and action='AUTH' ;
else
select COUNT(id) from xxx where app_id ='ABC' and date(creation_date) between '$(date +%F -d "tomorrow -30 days")' and '$(date +%F)' and action='AUTH' ;
fi
EOF
请帮我解决这个查询。或者更正这个代码,我是 shell 脚本的新手。
提前致谢!!!!!!!
解决方案
Mysql 无法理解 if ..else shell 语法,因此您需要在每个 if 中执行 mysql,否则使用 -e 阻止执行,例如:
...
elseif [ "$(date +%m)" -eq 2 ]
then
mysql --login-path=local -e "use testdb;select COUNT(id) from xxx where app_id ='ABC' and date(creation_date) between '$(date +%F -d "tomorrow -28 days")' and '$(date +%F)' and action='AUTH' ;" >> /home/test.sql
else
...
推荐阅读
- c++ - SourceLink:PDB 文件名大小写与存储库不匹配,破坏 SourceLink
- angular - 我可以根据屏幕尺寸调整垫表的显示列吗?
- git - 如何删除远程主分支?
- python - 如何在 pandas 的 pivot_table 中将值显示为不同的颜色?
- flutter - Flutter - 如何使用 FlipCard 将上一张卡片翻转回来
- javascript - Uncaught ReferenceError: "function" is not defined ES6 模块
- python-3.x - 使用 cron 执行 python 脚本
- react-native - 如何从 IOS 原生模块(插件)调用 react-native 函数
- sql - PostgreSQL 相当于 MongoDB 的 Mongoose?
- curl - netcdf 配置/编译:curl 错误,但已安装