I've found that an easy way to at least get started in the right direction for problems like this it to print out the query or statement to stdout. Then cut and paste it onto the command line of mysql. Often after doing this it's more obvious what I'm doing wrong.