Fix ORDER BY in many-to-many queries

And a couple other minor things noticed along the way.