How to convert a complex select query to Drupal dynamic query?
Give a try to Query coder module ( https://www.drupal.org/project/query_coder ): Convert SQL query to Drupal Database abstraction layer code.





Otherwise to debug the error turn on the error reporting, and check the error log which will point you to the suitable path.