项目场景:
项目场景:测试想根据一组id
获取name
做测试,由于各种原因(数据量大,sql
语句复杂),只能根据id
一条条查,于是写了个脚本:
解决方案一:
- 先查询需要的
id
导出到user_id.csv
文件
[root@VM-4-13-centos 0903]# cat user_id.csv
1
2
3
- 脚本(示例):
#!/bin/bash
cat user_id.csv | while read line
do
#打印每一行数据
echo "userId is : ${line}"
#编写SQL
sql="select id,name from test_2.student where id=${line} limit 1"
cnt=$(mysql -h127.0.0.1 -uroot -ppassword -s -e "${sql}" 2>/dev/null | grep -v cnt )
if [[ -z "$cnt" ]]
then
echo result is null
continue
fi
echo ${cnt} >> ok.txt
done
测试结果:
[root@VM-4-13-centos 0903]# sh test.sh
userId is : 1
userId is : 2
userId is : 3
[root@VM-4-13-centos 0903]# ls
ok.txt test.sh user_id.csv
[root@VM-4-13-centos 0903]# cat ok.txt
1 白杰
2 连宇栋
3 邸志伟
跟数据库对比发现结果一致
解决方案二:
上面的方案因为需要每次跟数据库交互,因此时间花费很长。除非对时间不关心且每次生成的文件不一样可以使用,一般都使用数据库
in
关键字来解决这类问题。
- 使用
Notepad++
或者其他可以列运算的工具。这里以Notepad++
为例,按住ALT
,鼠标向下滑动,选中需要改动的所有列。
- 然后拼接SQL语句
select id,name
from test_2.student
where id in('1',
'2',
'3');
- 测试结果