Javascript SQL Query

Hi All

I'm trying to put a restriction on an Adv. Search Select filed, but I need to be able to do a sub query in the SQL look up and I don't know how to do this. On Cases I have created the Adv. Search Select field, but I want to lock it down to all records in a Custom Entity that match the company. But the Custom entity doesn't hold the Comp ID value, this is held in middle table (TableA) 

For example below are three tables and I need to get the records out of TableB going via TableA

Cases = case_primarycompanyid

TableA = TA_TableAID and  TA_companyid

TableB (the one I want to get to) = TB_TableBID and TA_TableAID