Using PHP you could do something like this:
$Host = "your-mysql-host";
$User = "mysql-username";
$Password = "mysql-password";
$DBName = "your-db-name";
$TableName = "your-db-table";
$Link = mysql_connect ($Host, $User, $Password);
$Query = "SELECT * from $TableName LIMIT 1";
$Result = mysql_db_query ($DBName, $Query, $Link);
$intResults = mysql_num_rows($Result);
select * into outfile '/tmp/file2'
FIELDS TERMINATED BY ';' LINES TERMINATED BY '\N' FROM DIRECT_REFERRAL
This would basically do a general select from the DB table. Set the number or results found to a variable called $intResults. Then use an if statement that says if your query generated at least 1 result, then create the csv file.