¿ How to route calls dynamically depending of the provider?

Hi.
I have 3 providers of mobile telephony in Mexico(Telcel, Movistar & Iusacell), each company have prices that are lower if the call are between phone numbers of the same company, but more higher with another companys. In Asterisk PBX I have 3 Telular connected to a FXO port, each telular is to make calls for Movistar, Telcel or Iusacell by mean telulars. Queryng a database I Know if a number is from Movistar, Telcel or Iusacell, then when I dial the number -all mobile phone numbers in México begin with 044 or 045- I want query the mysql database to know what company is the number dialed and make a call with the FXO port where are the telular connected to the company of the dialed number.

You have any idea how to solve this problem ?

I hope can give me a tip or trick to develop a script with agis or macros.

Thanks.

Regards…