14

I am unable to make the following query work in drupal7 standards..Can anyone help me with this? Its little urgent...

SELECT n.nid AS nid, n.title AS title, count(n.title) AS ncount 
FROM node n 
INNER JOIN taxonomy_index tn ON n.nid = tn.nid 
WHERE (n.type = 'test') 
AND (tn.tid IN( 23,37)) 
AND (n.title LIKE '%name%') 
AND (n.status = 1) 
GROUP BY n.nid 
HAVING ncount = 2
24

This is off the top of my head so use caution...

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

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

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

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

$results = $query->execute();
  • Thanks, Clive! One additional common element: to sort by the count I added $query->orderBy('ncount', 'DESC'); – greggles Aug 17 '16 at 23:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.