我不是 bash 专家,但我做事循序渐进(其他专家可以编辑和改进我的答案)
#!/bin/bash
mysql -uusrname -ppassword -Ddatabasename -s -e 'show tables'
count=0
while read tablenames
do
fieldname=$(mysql -uusrname -ppassword -Ddatabasename -s -e "desc $tablename" | head -2 | tail -1 | awk -F " " '{print $1}');
echo "$tablenames,$fieldname" >> tempfile
done< $(mysql -uusrname -ppassword -Ddatabasename -s -e 'show tables')
lastcount=$(wc -l tempfile)
while read line
do
count=$(($count + 1))
if [ $count -eq 1 ]
then
echo "nothing to do"
elif [ $count -lt $lastcount ]
then
echo $line | awk -F "," '{print "(select "$2 "from" $1")"}' >> sqlcommand.sql
echo "union" >> sqlcommand.sql
else
echo $line | awk -F "," '{print "(select "$2 "from" $1");"}' >> sqlcommand.sql
done < tempfile
mysql -uusrname -ppassword -Ddatabasename << sqlcommand.sql >> outputasciifile.txt