Generally when you start naming variables with numeric suffixes (`r2` and `id2`, you're missing the chance to use a loop and/or an array).  In this case, you could loop over the two tables pretty easily.  But, at the end you have two IDs and only return one.  What's that return value used for, and does it need to be changed to a tuple?