I'm afraid there are too many levels of $_ for me to want to try to read your code, perhaps you'd also have an easier time reading it if you named your variables. Also, you did a pretty good job of describing what you want to happen, but you didn't describe how the behaviour of your script is different from that. Does your script misbehave, if so, how does the output differ from what you expect?
You may also want to look at the various modules on CPAN which buitl SQL queries from perl structures (e.g. SQL::QueryBuilder::Simple)