SELECT s.*, ss.*, IF(s.ext_id LIKE '%hnd_%', 0, 1) as self_stuff, IF(s.price='0.00', 0, 1) as price_flag, IF(sku_group='', IF(ext_id != '', ext_id,, sku_group) AS tmp_sku_group FROM shop s, shop_osnovnaya ss, pages g WHERE (( s.cat_id='40260' OR s.cat_id='40172' OR s.cat_id='31100' OR s.cat_id='40181' OR s.cat_id='40182' OR s.cat_id='40183' OR s.cat_id='40184' OR s.cat_id='40173' OR s.cat_id='40174' OR s.cat_id='40175' OR s.cat_id='40176' OR s.cat_id='40127' OR s.cat_id='31101' OR s.cat_id='31120' OR s.cat_id='40177' OR s.cat_id='40180' OR s.cat_id='40178' OR s.cat_id='40179' OR s.cat_id='40056' OR s.cat_id='40263' OR s.cat_id='40264' OR s.cat_id='40265' OR s.cat_id='40255' OR s.cat_id='40256' OR s.cat_id='40284' OR s.cat_id='40289' OR s.cat_id='40290' OR s.cat_id='40286' OR s.cat_id='40285' OR s.cat_id='40288' )) AND AND GROUP BY tmp_sku_group ORDER BY self_stuff, ss._count DESC, s.group_id , ASC, g.sort LIMIT 0, 40