Index: modules/taxonomy/taxonomy.module
===================================================================
RCS file: /cvs/drupal/drupal/modules/taxonomy/taxonomy.module,v
retrieving revision 1.442
diff -u -p -r1.442 taxonomy.module
--- modules/taxonomy/taxonomy.module	13 Nov 2008 08:13:56 -0000	1.442
+++ modules/taxonomy/taxonomy.module	20 Nov 2008 14:55:29 -0000
@@ -928,49 +928,25 @@ function taxonomy_get_synonym_root($syno
  */
 function taxonomy_term_count_nodes($tid, $type = 0) {
   static $count;
-
-  if (!isset($count[$type])) {
-    // $type == 0 always evaluates TRUE if $type is a string
-    if (is_numeric($type)) {
-      $result = db_query(db_rewrite_sql('SELECT t.tid, COUNT(n.nid) AS c FROM {term_node} t INNER JOIN {node} n ON t.vid = n.vid WHERE n.status = 1 GROUP BY t.tid'));
-    }
-    else {
-      $result = db_query(db_rewrite_sql("SELECT t.tid, COUNT(n.nid) AS c FROM {term_node} t INNER JOIN {node} n ON t.vid = n.vid WHERE n.status = 1 AND n.type = '%s' GROUP BY t.tid"), $type);
-    }
-    $count[$type] = array();
-    while ($term = db_fetch_object($result)) {
-      $count[$type][$term->tid] = $term->c;
-    }
-  }
-  $children_count = 0;
-  foreach (_taxonomy_term_children($tid) as $c) {
-    $children_count += taxonomy_term_count_nodes($c, $type);
-  }
-  return $children_count + (isset($count[$type][$tid]) ? $count[$type][$tid] : 0);
-}
-
-/**
- * Helper for taxonomy_term_count_nodes(). Used to find out
- * which terms are children of a parent term.
- *
- * @param $tid
- *   The parent term's ID
- *
- * @return array
- *   An array of term IDs representing the children of $tid.
- *   Results are statically cached.
- *
- */
-function _taxonomy_term_children($tid) {
-  static $children;
-
-  if (!isset($children)) {
-    $result = db_query('SELECT tid, parent FROM {term_hierarchy}');
-    while ($term = db_fetch_object($result)) {
-      $children[$term->parent][] = $term->tid;
+  $term = taxonomy_term_load($tid);
+  $tree = taxonomy_get_tree($term->vid, $tid);
+  $tids = array($tid);
+  foreach ($tree as $descendent) {
+    $tids[] =  $descendent->tid;
+  }
+
+  if (!isset($count[$type][$tid])) {
+    $query = db_select('term_node', 't');
+    $query->addExpression('COUNT(DISTINCT(t.nid))', 'nid_count');
+    $query->join('node', 'n', 't.vid = n.vid');
+    $query->condition('t.tid', $tids, 'IN');
+    $query->condition('n.status', 1);
+    if (!is_numeric($type)) {
+      $query->condition('n.type', $type);
     }
+    $count[$type][$tid] = $query->execute()->fetchField();
   }
-  return isset($children[$tid]) ? $children[$tid] : array();
+  return $count[$type][$tid];
 }
 
 /**
