Cleaning up sql query for hoards core

Lots of cross referencing needed.