Updated

Jose Guillen hit a go-ahead, two-run single in the seventh inning and the San Francisco Giants beat the Arizona Diamondbacks 9-7 on Sunday after wasting a fine outing by pitcher Matt Cain.

Freddy Sanchez added three hits and two RBIs for the Giants, who avoided being swept by the last-place Diamondbacks and pulled within five games of San Diego in the NL West.

San Francisco remained 1½ games behind Philadelphia for the NL wild card.

Stephen Drew had four hits for Arizona, including his 11th home run of the season.

Jeremy Affeldt (3-3) got two outs for the win while Brian Wilson recorded the final five outs for his 36th save in 38 tries.

The Giants dropped the first two games of the series after their starting pitchers struggled to get out of the first inning. Tim Lincecum and Barry Zito allowed a combined nine runs in the opening frame and both took the loss.

This time it was San Francisco's bullpen that fell apart and nearly proved costly until Guillen bailed the Giants out.

Guillen, acquired from Kansas City on Aug. 13 after being designated for assignment, couldn't get the ball out of the infield in his first three at-bats before singling off Esmerling Vasquez (1-5) to drive in Sanchez and Aubrey Huff. Guillen later scored on a sacrifice fly by Cody Ross.

Cain pitched 6 1-3 solid innings, scattering six hits while striking out seven. He left with a 5-2 lead and a runner on first before San Francisco's normally reliable relievers fell apart.

Manager Bruce Bochy's bullpen had been solid in August, going 6-1 with a 3.26 ERA in 25 games but stumbled against Arizona. The Diamondbacks scored three runs in the seventh after Cain left, taking a 6-5 lead on Adam LaRoche's two-run double.

The two RBIs give LaRoche 87 for the season, tying Tony Clark's franchise record for first basemen set in 2005.

The Giants answered with three runs in the bottom half and held on for the victory.

Drew homered off Cain leading off the third, then Arizona got some help from the Giants pitcher to score its second run.

Cain struck out pinch-hitter Ryan Church but the ball skipped past catcher Eli Whiteside, allowing Church to reach first on the wild pitch. Church took second and third when Cain uncorked two more wild pitches and scored on Drew's grounder.

San Francisco scored four runs in the third off Arizona starter Rodrigo Lopez.

NOTES: Bochy said he expects LHP Dan Runzler to be activated from the disabled list Wednesday when rosters are expanded. ... Guillen is batting .372 in 13 games with the Giants. ... Lopez lasted four innings and gave up five runs and eight hits and is winless in his last nine starts.