@@ -375,35 +375,57 @@ private function getCountFromCategoryTableBulk(
375375 array $ categoryIds ,
376376 int $ websiteId
377377 ) : array {
378- $ subSelect = clone $ this ->_conn ->select ();
379- $ subSelect ->from (['ce2 ' => $ this ->getTable ('catalog_category_entity ' )], 'ce2.entity_id ' )
380- ->where ("ce2.path LIKE CONCAT(ce.path, '/%') OR ce2.path = ce.path " );
381-
382- $ select = clone $ this ->_conn ->select ();
383- $ select ->from (
378+ $ connection = $ this ->_conn ;
379+ $ tempTableName = $ connection ->getTableName ('temp_category_descendants_ ' . uniqid ());
380+ $ connection ->query ("CREATE TEMPORARY TABLE {$ tempTableName } (
381+ category_id INT UNSIGNED NOT NULL,
382+ descendant_id INT UNSIGNED NOT NULL,
383+ PRIMARY KEY (category_id, descendant_id)
384+ ) " );
385+ $ selectDescendants = clone $ connection ->select ();
386+ $ selectDescendants ->from (
384387 ['ce ' => $ this ->getTable ('catalog_category_entity ' )],
385- 'ce.entity_id '
386- );
387- $ joinCondition = new \Zend_Db_Expr ("cp.category_id IN ( {$ subSelect }) " );
388- $ select ->joinLeft (
389- ['cp ' => $ this ->getProductTable ()],
390- $ joinCondition ,
391- 'COUNT(DISTINCT cp.product_id) AS product_count '
388+ ['category_id ' => 'ce.entity_id ' , 'descendant_id ' => 'ce2.entity_id ' ]
389+ )
390+ ->joinInner (
391+ ['ce2 ' => $ this ->getTable ('catalog_category_entity ' )],
392+ 'ce2.path LIKE CONCAT(ce.path, \'/% \') OR ce2.entity_id = ce.entity_id ' ,
393+ []
394+ )
395+ ->where ('ce.entity_id IN (?) ' , $ categoryIds );
396+ $ connection ->query (
397+ $ connection ->insertFromSelect (
398+ $ selectDescendants ,
399+ $ tempTableName ,
400+ ['category_id ' , 'descendant_id ' ]
401+ )
392402 );
403+ $ select = clone $ connection ->select ();
404+ $ select ->from (
405+ ['t ' => $ tempTableName ],
406+ ['category_id ' => 't.category_id ' ]
407+ )
408+ ->joinLeft (
409+ ['cp ' => $ this ->getTable ('catalog_category_product ' )],
410+ 'cp.category_id = t.descendant_id ' ,
411+ ['product_count ' => 'COUNT(DISTINCT cp.product_id) ' ]
412+ );
393413 if ($ websiteId ) {
394414 $ select ->join (
395415 ['w ' => $ this ->getProductWebsiteTable ()],
396416 'cp.product_id = w.product_id ' ,
397417 []
398- )->where (
399- 'w.website_id = ? ' ,
400- $ websiteId
401- );
418+ )->where ('w.website_id = ? ' , $ websiteId );
419+ }
420+ $ select ->group ('t.category_id ' );
421+ $ result = $ connection ->fetchPairs ($ select );
422+ $ connection ->query ("DROP TEMPORARY TABLE {$ tempTableName }" );
423+ $ counts = array_fill_keys ($ categoryIds , 0 );
424+ foreach ($ result as $ categoryId => $ count ) {
425+ $ counts [$ categoryId ] = (int )$ count ;
402426 }
403- $ select ->where ('ce.entity_id IN(?) ' , $ categoryIds );
404- $ select ->group ('ce.entity_id ' );
405427
406- return $ this -> _conn -> fetchPairs ( $ select ) ;
428+ return $ counts ;
407429 }
408430
409431 /**
0 commit comments