Don’t use the query inside any for loops. Instead, query the list of all records and store it in a list or set, and loop through that list to do the set of logic you wanted to do. No queries inside a for loop is the ground rule for apex programming. Google examples for this approach, there are plenty of examples you can find. Happy coding.