How to write a Drupal 7 query with "count" and "having" properties?
This is off the top of my head so use caution...

$query = db_select('node', 'n')
  -&gt;fields('n', array('nid', 'title'))
  -&gt;condition('n.type', 'test')
  -&gt;condition('tn.tid', array(23, 37))
  -&gt;condition('n.title', '%' . db_like('name') . '%', 'LIKE')
  -&gt;condition('n.status', 1)
  -&gt;groupBy('n.nid');

// Add the COUNT expression
$query-&gt;addExpression('COUNT(n.title)', 'ncount');

// Add the HAVING condition
$query-&gt;havingCondition('ncount', 2);

// Add the JOIN
$query-&gt;join('taxonomy_index', 'tn', 'n.nid = tn.nid');

$results = $query-&gt;execute();