Rewritten the query to allow mysql to use indexes

On a system with heavy logging, without this the login procedure took
too long.