The story goes that when Vishnu saw Kartikeya cuddling in the lap of Parvati, he desired to experience the bliss of being the son of Jagadamba and drink her nectar milk. The Goddess sensed this desire of Vishnu and granted him the boon that he'll surely become her son.
Thus, the Goddess gave birth to Ganesha who was none other than Sri Hari himself. She embraced him and made him drink her milk. After Shiva had beheaded Ganesha, he apologized to Vishnu that just as he has beheaded him in the form of Ganesha, a time will come when Vishnu will incarnate as Sri Krishna. As Krishna, he'll come to battle with Shiva in Shonitpura, and there, the weapon of Krishna will benumb Shiva so that he'll be unable to further fight in the battle. He will equate himself with Vishnu in knowledge, culture, wisdom, prowess.this is the reason why Ganesh is 2nd most intelligent being after Mahavishnu