Make sorting work as expected for forign key columns.

Sorting foreign key columns used to sort on the foreign
key itself instead of on the value shown to the user.
This patch fixes this.

Note that the tablename is always quoted in the query,
as -- contrary to the comment some lines above -- the
tablename wasn't quoted at all. And now we have another
potential tablename, so I hope no one 'fixes' the code
to correspond to that comment. I'll try to address that
in a seperate patch.