Optimized queries via replacing selects with joins