/**
  * Clean unused relation products
  *
  * @param int $storeId
  * @return Enterprise_Catalog_Model_Index_Action_Product_Flat_Refresh
  */
 protected function _cleanRelationProducts($storeId)
 {
     if (!$this->_productHelper->getFlatHelper()->isAddChildData()) {
         return $this;
     }
     foreach ($this->_getProductTypeInstances() as $typeInstance) {
         if (!$typeInstance->isComposite()) {
             continue;
         }
         $relation = $typeInstance->getRelationInfo();
         if ($relation && $relation->getTable() && $relation->getParentFieldName() && $relation->getChildFieldName()) {
             $select = $this->_connection->select()->distinct(true)->from($this->_productHelper->getTable($relation->getTable()), "{$relation->getParentFieldName()}");
             $joinLeftCond = array("e.entity_id = t.{$relation->getParentFieldName()}", "e.child_id = t.{$relation->getChildFieldName()}");
             if ($relation->getWhere() !== null) {
                 $select->where($relation->getWhere());
                 $joinLeftCond[] = $relation->getWhere();
             }
             $entitySelect = new Zend_Db_Expr($select->__toString());
             $select = $this->_connection->select()->from(array('e' => $this->_productHelper->getFlatTableName($storeId)), null)->joinLeft(array('t' => $this->_productHelper->getTable($relation->getTable())), implode(' AND ', $joinLeftCond), array())->where('e.is_child = ?', 1)->where('e.entity_id IN(?)', $entitySelect)->where("t.{$relation->getChildFieldName()} IS NULL");
             $sql = $select->deleteFromSelect('e');
             $this->_connection->query($sql);
         }
     }
     return $this;
 }