To explore the relationship between myopia and green space, and the mediation effects of outdoor time. We used large-scale, cross-sectional observational data from Shanghai, China. Participants were aged 3~20 years and underwent visual acuity and non-cycloplegic refraction in 2021. Using GIS-based data on environments surrounding participants' schools and kindergartens, we examined the association between green space (measured by NDVI) and myopia. We employed a logistic mixed-effects model to assess the impact of school-level green environments on individual myopia, reporting odds ratios (OR) and their 95% confidence intervals. Mediation analysis was conducted to explore whether outdoor activity time mediates the relationship between green environments and myopia. Additionally, we conducted age- and gender-stratified analyses and validated the robustness of the model through sensitivity analysis. Complete case sample sizes were 1,727,709 from 3,399 schools and kindergartens [899,817 (52.082%) boys; mean age 10.065 years (SD: 3.633)]. NDVI within 1000 m of schools was independently associated with lower odds of myopia (OR: 0.299, 95% CI: 0.249 ~ 0.357, p < 0.001), with 2.7% of the total effects attributed to the mediation effects of outdoor time. The effect sizes for NDVI were comparatively more protective in boys and those aged 7~12 years (OR: 0.223, 95% CI:0.156 ~ 0.319, p < 0.001). Sensitivity analysis with a 500-meter NDVI radius and alternative outcome variable of wearing glasses confirmed consistency with the previous results. This study demonstrates a significant impact of green environments on myopia in children and adolescents aged 3~20 years, revealing the potential mediating effect of outdoor activities. Policymakers should consider implementing intervention measures to enhance green spaces in schools to promote eye-health-friendly environments.