Chazal tell us that Korach mocked Moshe Rabeinu for requiring one to affix a mezuzah on the doorway of a room full of seforim. Although Korach was clearly incorrect and filling one’s dining room with sifrei kodesh does not exempt one from affixing a mezuzah; nonetheless, a shul or beis medrash may not require a mezuzah.
The gemara (Yoma 11b) equates the obligation of a house that requires a mezuzah to its susceptibility to tzaraas. Since a shul is not “your house” it is excluded from both of these halachos. Although by extension, this should also exempt a house owned by partners (as is the case with negaim), the Ritva explains that the derasha only extends as far as to define a house as one that is used privately.
Other rishonim exempt a shul from mezuzah because of its sanctity, like the beis hamikdash which is also exempt. Although the sanctity of a shul is only rabbinic in nature, the Chasam Sofer explains that the beis hamikdash is exempt not because of its inherent kedusha, but rather because it is the host to kedusha, although this would mean that a bedroom built on har habayis would require a mezuzah.
Others, (Tosfos haRosh, Chazon Ish) seem to understand that the exemption of a shuI from mezuzah stems from the laws of forced division or sale of property which does not apply to public property. Accordingly, a privately owned shul would require a mezuzah.
All agree, however, that a community shul does not require a mezuzah. Nevertheless, the custom is to affix a mezuzah without a beracha. The reason, according to most authorities, is because our shuls also function as a beis hamedrash with people learning within them at all hours. Although people learning at random would not necessitate a mezuzah, even a single talmid chacham who makes the beis medrash his home by learning throughout the day and/or eating and resting there, might, at least according to some rishonim (Maharam, cited by Shulchan Aruch), create an obligation.