Drupal - Is it possible to join dynamic tables (subqueries) using db_select()?

Both db_select and addJoin documentation says clearly that the table

May be a string or another SelectQuery object. If a query object is passed, it will be used as a subselect.

So,

$sub_select = db_select('comment');
// Convert.
$select = db_select('comment')->addJoin($sub_select...

I think you're looking for addJoin() ... I could be wrong ... here's a small example of adding a join to a db_select() from some random code I have ...

$query2 = db_select('dew_response', 'dr')->extend('TableSort')->orderByHeader($header);
$query2->addJoin('LEFT', 'dew_response_item', 'dri', 'dr.drid = dri.response_id');
$query2
  ->fields('dri', array('driid', 'item_id', 'response_id', 'answer'))
  ->fields('dr', array('drid'))
  ->condition('dri.survey_id', $survey_id, '=')
  ->condition('dri.response_id', $response_id, '=');
$result = $query2->execute();

Tags:

Database