use groupby+count+distinct to make search faster in postgresql; original one is much faster in sqlite but very slow in postgresql