How to loop SQL query in mysql?
Excuse the mess I am about to create, but here it goes ...

STEP 01

Create a file called /tmp/ProcessDate.sql which contains this

create temporary table tmp1(
...
where thedate=@thedate
);

create temporary table tmp2(
...
where thedate=@thedate
);

delete from tbl1;

replace into tbl1(
select * 
from tmp1
inner join tmp2
);


STEP 02

Create a Shell Script call /tmp/ProcessDays.sh which contains this

MYSQL_USER=root
MYSQL_PASS=rootpassword
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"

TS_NOW=`date +"%s"`
TS_NDX=1
TS_DAY=0

while [ ${TS_DAY} -lt ${TS_NOW} ]
do
    SQL="SELECT DATE(FROM_UNIXTIME((UNIX_TIMESTAMP(MAKEDATE(YEAR(NOW()),${TS_NDX})))))"
    DT=`mysql ${MYSQL_CONN} -ANe"${SQL}"`
    echo "SET @thedate = '${DT}';" &gt; /tmp/ProcessOneDay.sql
    cat /tmp/ProcessDate.sql &gt;&gt; /tmp/ProcessOneDay.sql
    OUTFILE=Data_${DT}.tsv
    mysql ${MYSQL_CONN} -AN &lt; /tmp/ProcessOneDay.sql
    mysql ${MYSQL_CONN} -AN"SELECT * FROM tbl" &gt; ${OUTFILE}
    (( TS_NDX++ ))
    SQL="SELECT UNIX_TIMESTAMP(MAKEDATE(YEAR(NOW(),1) + INTERVAL ${TS_NDX} DAY)"
    TS_DAY=`mysql ${MYSQL_CONN} -ANe"${SQL}"`
done


STEP 03 : GIVE IT A TRY !!!