Improve the performance of migration 186

This patch significantly improves the performance of migration 186 by
refactoring the migration code to use SQL joins. It does in no way
functionally change what the migration does.

It also adds a more robust test to make sure that there were no
regressions.

Change-Id: I654ed8dd229d774e8f680cae2b8d2ad2cf28550c
Merge "Improve the performance of migration 186"