It would be easier to put the command in a shell script and send the shell script over to run it. That way you avoid the multiple layers of shell interpretation.
You have to remember that EACH shell involved will remove a layer of escapes... So even to pass the first level you have to escape all the special characters (even the * ).
Another way to develop it is to build the script up in parts... when you get part of the script working, add the next part. But it is hard, and not secure. In the case of database operations you are also fighting the quoting done by two different shells; with three instance of shell interpretation:
1. local shell interpreting the command line for ssh.
2. remote shell interpreting the command to run the mysql command
3. the mysql command interpretation of its own command.
One way to avoid the first one is to try it this way:
where the file contains the mysql command "mysql -u root -ppassword ..." from your working local version. This avoids the problem of the local shell interpretation, and SHOULD allow the remote shell interpretation to work as the command would be local, but running on the host server1.
The security aspect gets in there because it is possible for the remote
shell (or local one for that matter) slipping in a substitution you don't intend - even including data for a mysql command (
http://xkcd.com/327/ for an example). This problem is unavoidable...
I have even run across one where an authors name caused a database failure (the author was of Chinese decent, and his name included an apostrophe...).