shell脚本循环执⾏mysql语句
参考资料:
需求:数据库⾥有张数据表存储的是⽤户对电影的评价(user_id movie_id rating time),但是我现在要每部电影的总评分。
解决⽅法:
1)、写个sql⽂件test.sql:use movie_recommendation;select distinct movie_id from T_user_movie_rating_map;
2)、在终端输⼊mysql -uroot -p123456 -e < test.sql >
  这样就会获得电影id的列表,然后编辑该⽂件把第⼀⾏的movie_id这个字符串删掉
3)、然后编辑如下shell脚本rating.sh:
1 #!/bin/bash
2
3for line in $(cat )
shell脚本返回执行结果
4do
5    result=$(mysql -uroot -p12345
6 -e "use movie_recommendation;select avg(rating) from T_user_movie_rating_map where movie_id=$line")
6    tmp=$(echo $result | sed's/ /\n/g')
7for tmp_line in $tmp
8do
9        result=$tmp_line
10done
11echo $line:$result
12echo $line,$result >>
13done
4)、在终端输⼊. ./rating.sh即可将电影id和电影对应的评分写⼊到指定⽂件夹下
说明:中间对result这个结果进⾏了处理,是因为查询数据库获得的结果有标题,需要去掉这个标题