I'm afraid I'm not entirely clear about your database structure or what exactly you are trying to do, so I can't really advise you on that. I can just look at the file and point out syntax errors.
If you want to do a premier support ticket on this then we can do screen sharing and I can take a look at your database and you can explain exactly what you are trying to do in context and I can help figure it all out.