MDL-42882 upgrade: improved SQL query

Kudos to Tim Hunt who came up with this, on mysql with 4 milion
records (and a fast SSD):

Original: 36.83 sec
New query: 8.63 sec