Read Rule 10.17. It’s all laid out for those brave enough to read it.
In general, a starting pitcher must pitch 5 or more innings and the team must be in the lead after 6 defensive innings and not relinquish the lead or have the score tied at any point after he leaves the game.
It gets murky when you have relievers and lead changes. Each time the score becomes tied, previous pitchers are no longer pitchers of record–including the losing pitcher if his team ties the game or takes the lead at any point after he leaves.
Relievers who split an inning where their team takes the lead, it can come down to which pitcher was “most effective” during their time on the mound. It can even be debatable if a future reliever is more effective than a prior reliever–even if the winning team took the lead during the first reliever’s time on the mound. There is even a “crucial out” criteria. If a reliever comes in bases loaded with no outs and does not give up a run and his team scores in the following inning and a new reliever takes the mound the following inning and holds the opposition to no runs, the reliever who got out of that major jam may be credited with the win.
It’s really up to the official scorer. Another example where a team hangs up a 5 in an inning, but the reliever gives up 4 runs and is yanked and the team retains the lead, he may be denied the win for being ineffective, even if the team was technically in the lead when he left.
Are you confused yet?