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='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