optimize foreign key query