Optimisation done as suggested by arthasdk, only one db call instead of n^2