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, s.id), sku_group) AS tmp_sku_group FROM shop s, shop_osnovnaya ss, pages g WHERE (( s.cat_id='40279' )) AND s.cat_id=g.id AND s.id=ss.id GROUP BY tmp_sku_group ORDER BY self_stuff, ss._count DESC, s.group_id , s.name ASC, g.sort LIMIT 0, 40