We have found that local galaxies follow a very tight relation between gas metallicity, stellar mass and SFR, suggesting that their evolution is characterized by a long standing equilibrium between gas inflows, outflows and star formation. Surprisingly, even distant galaxies, out to z < 2.5, follow the same relation, suggesting that the same dominant mechanism of galaxy evolution is in place at any epoch, out to z < 2.5. However, by using deep near-IR spectroscopy (probing optical nebular lines at high-z), we find that galaxies at z > 3 deviate from such fundamental relation, by being significantly more metal poor. Spatially resolved metallicity maps of z > 3 disk galaxies reveal that they are characterized by central regions with low metallicity associated with the peak of star formation, indicating that the latter is due to massive inflow of pristine gas that both boosts star formation and dilutes the gas metallicity. Overall these results suggest that the metallicity evolution of galaxies at z > 3 is due to an excess of gas inflow at such early epochs, as expected by some recent models. Finally, we investigate the metallicity of merging systems, both locally and at high-z. By exploiting recent Herschel data, we have found that in these systems the dust content directly measured through the FIR-submm data is much higher than inferred from the metallicity measured through the optical nebular lines. The latter result suggests that, in these heavily obscured systems, optical observations only probe the outer, less enriched regions and are not representative of the bulk of the metal content.