Merge pull request #2332 from colemanw/CRM-13996
[civicrm-core.git] / CRM / Contact / BAO / GroupContactCache.php
index 90b2cdd62ff403c2cd77cc0f6b5833f5b6df0d7e..be50a15fb4b64cbff433f3d1641f0d72a70ea789 100644 (file)
@@ -480,16 +480,22 @@ WHERE  civicrm_group_contact.status = 'Added'
 
     $groupIDs = array($groupID);
     self::remove($groupIDs);
-
     $processed = FALSE;
+    $tempTable = 'civicrm_temp_group_contact_cache' . rand(0,2000);
     foreach (array($sql, $sqlB) as $selectSql) {
       if (!$selectSql) {
         continue;
       }
-      $insertSql = "INSERT IGNORE INTO civicrm_group_contact_cache (group_id,contact_id) ($selectSql);";
+      $insertSql = "CREATE TEMPORARY TABLE $tempTable ($selectSql);";
       $processed = TRUE;
       $result = CRM_Core_DAO::executeQuery($insertSql);
+      CRM_Core_DAO::executeQuery(
+        "INSERT IGNORE INTO civicrm_group_contact_cache (contact_id, group_id)
+        SELECT DISTINCT $idName, group_id FROM $tempTable
+      ");
+      CRM_Core_DAO::executeQuery(" DROP TABLE $tempTable");
     }
+
     self::updateCacheTime($groupIDs, $processed);
 
     if ($group->children) {