In prison God showed mercy on Joseph.
Now we might ask why didn't God show mercy by not letting him go into the pit, or into the prison or face false accusations.
Well he was in the pit for a lesson, he was in the prison to learn. He was a sojourner there getting ready for his place, While God got his place ready for him.
He was never intended to stay in the pit, or to stay in the prison they were stepping stones on the way to God's plan for his life.