Optimize queries with inner join