Minimize number of MySQL queries in agent check

Fixes issue #591.