Bug fixes for mysql queries