SELECT (@pos:=@pos+1) as ord, coupon.id as CID, coupon.name as name, UNIX_TIMESTAMP(coupon.effective) as effective, UNIX_TIMESTAMP(coupon.expiration) as expiration, (coupon.flags ^ 1) as ACTIVE, (coupon.flags ^ 2) DIV 2 as COMMENTS_ENABLED, #NOT IMPLEMENTED ((coupon.flags ^ 4) DIV 4) as UNDEFINED4, ((coupon.flags ^ 8) DIV 8) as UNDEFINED8, ((coupon.flags ^ 16) DIV 16) as UNDEFINED16, ((coupon.flags ^ 32) DIV 32) as UNDEFINED32, ((coupon.flags ^ 64) DIV 64) as UNDEFINED64, ((coupon.flags ^ 128) DIV 128) as UNDEFINED128, coupon.description_text as description_text, business.name as bname, business.id as BID, subcategory.name as catname2, category.name as catname1, coupon.img_id as IID, coupon.id as x, ( select count( * ) from `access` where access.coupon_id = x group by coupon.id ) as views, ( select count( * ) from `vote_coupon` where vote_coupon.coupon_id = x group by coupon.id ) as votes, ( select ( 30 - ( to_days( expiration ) - to_days( FROM_UNIXTIME('1180567638') ) ) ) from `coupon` where ( expiration - FROM_UNIXTIME('1180567638') ) <= 30 and coupon.id = x group by coupon.id ) as date_relevance, ( select ( votes * .75 ) + ( date_relevance * .15 ) + ( views * .10 ) ) as score, ( SELECT (count( * ) + 1) FROM (SELECT coupon.id AS CID, coupon.name AS name, UNIX_TIMESTAMP(coupon.effective) AS effective, UNIX_TIMESTAMP(coupon.expiration) AS expiration, coupon.id AS y, ( SELECT ( ( SELECT count( * ) FROM `vote_coupon` WHERE vote_coupon.coupon_id = y ) * .75 ) + ( ( SELECT ( 30 - ( to_days( expiration ) - to_days( now() ) ) ) FROM `coupon` WHERE ( expiration - now() ) <= 30 AND coupon.id = y GROUP BY coupon.id ) * .15 ) + ( ( SELECT count( * ) FROM `access` WHERE access.coupon_id = y ) * .10 ) ) AS y_score FROM `coupon` , `subcategory` , `category` , `business` WHERE coupon.effective <= now() AND coupon.expiration >= now() AND (SELECT (coupon.flags ^ 1)) GROUP BY coupon.id HAVING y_score > score LIMIT 0,10 ) v1 ) as rank FROM `coupon` , `subcategory` , `category` , `business` WHERE subcategory.id = coupon.subcategory_id AND category.id = coupon.category_id AND coupon.business_id = business.id AND coupon.effective <= FROM_UNIXTIME('1180567638') AND coupon.expiration >= FROM_UNIXTIME('1180567638') AND (SELECT (coupon.flags ^ 1)) #ACTIVE GROUP BY coupon.id ORDER BY score DESC LIMIT 0, 3