SELECT `link`, `link_r` FROM (SELECT `cpl_link_offer`.`link` , `cpl_offer_cpa`.`link` as `link_r` FROM `cpl_link_offer` JOIN `cpl_offer_cpa` ON `cpl_link_offer`.`offer_id` = `cpl_offer_cpa`.`offer_id` JOIN `cpl_cpa` ON `cpl_cpa`.`name` = `cpl_offer_cpa`.`cpa` ORDER BY `cpl_offer_cpa`.`rating` DESC, `cpl_cpa`.`rating` DESC) AS `t1` GROUP BY `link`