FROM ( full text of query 1 )
WHERE (condition 1)
FROM ( full text of query 2 )
WHERE (condition 2)
AND NOT (condition 1)
Neither condition must give NULL (due to NULL in field/variable values) in NOT.
Outer SELECTs for each separate subquery in UNION may be excess if separate queries are not complex.
For the code shown in ...
This is yet another installment of the MySQL sql_mode = only_full_group_by saga.
The problem is that MySQL's default (till 8) will return results which, depending on the order of the records being INSERTed into the table (and/or PRIMARY KEY ordering), will vary and be correct or wrong DEPENDING. This is absolutely the worst sort of difficult to ...