Update table from a join which returns multiple rows for each result
Combine the rows of B (GROUP BY a_fk); in the process decide whether to keep Y or NULL.
Store the result of that into a temp table.
Then do the original UPDATE, but against the temp table.
So two statements, no looping:
CREATE TEMPORARY TABLE t
    SELECT ...
        GROUP BY a_fk;
UPDATE A JOIN t ON ...
    SET A... = t...;