I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres. SELECT ...
stackoverflow.com