Fix inefficient and wrong DB query. Thanks to jhlj and tgc for the identification of the problem and the patch