if else loop only iterating once
Don't do it in a loop.  Do it in a single multi-table UPDATE and/or INSERT ... SELECT ... LEFT JOIN ... IS NULL.

More details:  http://mysql.rjweb.org/doc.php/staging_table#normalization