Praise be to Allah.If a person joins the imaam whilst he is praying Ishaa, but he has missed Maghrib for some legitimate reason, such as travelling, etc., then he should pray Maghrib even if the imaam is praying Ishaa, because the prayers have to be kept in the proper order. This is what the Prophet (peace and blessings of Allaah be upon him) did during the campaign of al-Khandaq. Jaabir ibn Abd-Allaah said: Umar came on the day of al-Khandaq cursing the kuffaar of Quraysh and saying, O Messenger of Allaah, I did not pray Asr until the sun was almost setting. The Prophet (peace and blessings of Allaah be upon him) said, By Allaah, I have not prayed it yet either. So he went down to But-haan [the name of a valley], did wudoo and prayed Asr after the sun had set, then he prayed Maghrib. (Reported by al-Bukhaari, 893)
Al-Haafiz ibn Hajar said in al-Fath: This hadeeth teaches us how to make up missed prayers in order, and most scholars agree that this [keeping prayers in order] is obligatory.
Al-Bukhaari included this hadeeth in a chapter entitled Baab Qada al-Salawaat al-Oolaa fal-Oolaa (Chapter on making up prayers in order).
In the case mentioned in the question, it is permissible for you to pray Maghrib behind an imaam who is praying Ishaa, but when he gets up for the fourth rakah, you should remain sitting and recite the Tashahhud, and it is better to wait until he sits and says the Tasleem, so that you say the Tasleem with him. Then you should go ahead and pray Ishaa. And Allaah knows best.