Mary was related to David, too, but by a different line. Joseph was descended from David's son Solomon, while Mary was descended from a son called Nathan (not the famous prophet, but another one).
Anyway the two genealogies (from Matthew and Luke) are almost totally different, leading to the surmise that they are from Joseph's side and Mary's side, respectively. Certain details in the wording also suggest this. However, I don't know if anybody has ruled on this definitively or produced dispositive proof.
Thanks for the clarification. It’s an interesting subject.