Basically you need to use a regular foreach instead of db_foreach.
In your case I suggest selecting the outer dataset in a multirow with db_multirow, then using template::multirow::foreach on that multirow data.
If you have a list of ids or another single column to loop over in the outer loop, you can just use db_list instead of db_multirow for the outer query.