Germany coach Julian Nagelsmann made five substitutions in a desperate attempt to find the equaliser which paid dividends in the 89th minute as substitute Florian Wirtz, the Bundesliga’s player of the year for champions Bayer Leverkusen, hammered home a shot from Joshua Kimmich’s header to force extra time.
The game was into the 119th minute and looked set for a penalty shoot-out when substitute Merino rose to head home the winning goal from Olmo’s cross.
The hosts Germany pushed hard for a late leveller and fullback Dani Carvajal was sent off after receiving a second yellow card for tackling Jamal Musiala to avoid a counter attack.
He and centre back Robin Le Normand will miss the semifinal, as Spain held out to advance to the last four and a meeting with either Portugal or France.
GIPHY App Key not set. Please check settings