From cbe32e2f630683cc4749a9eb59745aa59e03eac8 Mon Sep 17 00:00:00 2001 From: Coleman Watts Date: Fri, 24 Oct 2014 08:44:56 -0400 Subject: [PATCH] CRM-15107 - Fix slow group_contact count query on large dbs --- CRM/Contact/BAO/Group.php | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) 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; } -- 2.25.1