Change nested query to query with inner join