build query with select and joins