From: Coleman Watts Date: Fri, 24 Oct 2014 12:44:56 +0000 (-0400) Subject: CRM-15107 - Fix slow group_contact count query on large dbs X-Git-Url: https://vcs.fsf.org/?a=commitdiff_plain;h=cbe32e2f630683cc4749a9eb59745aa59e03eac8;p=civicrm-core.git CRM-15107 - Fix slow group_contact count query on large dbs --- diff --git a/CRM/Contact/BAO/Group.php b/CRM/Contact/BAO/Group.php index 75332c0c9f..8743a3131e 100644 --- a/CRM/Contact/BAO/Group.php +++ b/CRM/Contact/BAO/Group.php @@ -831,12 +831,8 @@ class CRM_Contact_BAO_Group extends CRM_Contact_DAO_Group { } $query = " - SELECT groups.*, createdBy.sort_name as created_by, IF(groups.saved_search_id, COUNT(smart_contacts.id), COUNT(contacts.id)) as `count` {$select} + SELECT groups.*, createdBy.sort_name as created_by {$select} FROM civicrm_group groups - LEFT JOIN civicrm_group_contact contacts - ON contacts.group_id = groups.id AND contacts.status = 'Added' - LEFT JOIN civicrm_group_contact_cache smart_contacts - ON smart_contacts.group_id = groups.id LEFT JOIN civicrm_contact createdBy ON createdBy.id = groups.created_id {$from} @@ -861,7 +857,7 @@ class CRM_Contact_BAO_Group extends CRM_Contact_DAO_Group { $links = self::actionLinks(); $allTypes = CRM_Core_OptionGroup::values('group_type'); - $values = array(); + $values = $groupsToCount = array(); $visibility = CRM_Core_SelectValues::ufVisibility(); @@ -873,7 +869,10 @@ class CRM_Contact_BAO_Group extends CRM_Contact_DAO_Group { if ($permission) { $newLinks = $links; - $values[$object->id] = array('class' => array()); + $values[$object->id] = array( + 'class' => array(), + 'count' => '0', + ); CRM_Core_DAO::storeValues($object, $values[$object->id]); if ($object->saved_search_id) { $values[$object->id]['title'] .= ' (' . ts('Smart Group') . ')'; @@ -917,7 +916,7 @@ class CRM_Contact_BAO_Group extends CRM_Contact_DAO_Group { $values[$object->id]['visibility'] = $visibility[$values[$object->id]['visibility']]; - $values[$object->id]['count'] = $object->count; + $groupsToCount[$object->saved_search_id ? 'civicrm_group_contact_cache' : 'civicrm_group_contact'][] = $object->id; if (isset($values[$object->id]['group_type'])) { $groupTypes = explode(CRM_Core_DAO::VALUE_SEPARATOR, @@ -973,6 +972,14 @@ class CRM_Contact_BAO_Group extends CRM_Contact_DAO_Group { } } + // Get group counts + foreach ($groupsToCount as $table => $groups) { + $dao = CRM_Core_DAO::executeQuery("SELECT group_id, COUNT(id) as `count` FROM $table WHERE group_id IN (" . implode(',', $groups) . ") GROUP BY group_id"); + while($dao->fetch()) { + $values[$dao->group_id]['count'] = $dao->count; + } + } + return $values; }