Use IDatabase::selectSQLText for the sub query
Rather than manually stringing things together.
Additionally, since there is support for table aliases in the
database abstraction layer, use that, rather than raw SQL fragments.
This ensures table names are quoted and prefixed where necessary, while
also improving database backend compatibility.