When you shift your focus to someone else in pain, you take your mind off of your pain. The compassion you mentally extend to them will alleviate your pain.
Having wise selfishness will help you achieve joy and happiness in the long run, but being foolishly selfish will ensure you never experience lasting joy or happiness. This is because when you focus and obsess about yourself and your desires, you will experience suffering.
Remember, humans are social creatures. We need friends—genuine friends. The only way to do this is to trust in others and help them. This is actually supported by scientific research: those who think about themselves tend to be socially withdrawn and unhappy, but those who are sociable and creative tend to be happy!