Nested loops and SQL queries; need for speed

I’m having trouble solving a problem with iterative SQL queries (which I need to do away with) and I’m trying to work out an alternative.(Also; unfortunately, AJAX is not really suitable)Given...