Bug fix for multi-table query