Start with a query which returns only those Table2
rows which are not matched in Table1
.
SELECT t2.FirstName, t2.LastName
FROM
Table2 AS t2
LEFT JOIN Table1 AS t1
ON
t2.FirstName = t1.FirstName
AND t2.LastName = t1.LastName
WHERE t1.FirstName Is Null;
Then use that SELECT
in your UNION
query.
SELECT FirstName, LastName, PhoneNumber FROM Table1
UNION ALL
SELECT t2.FirstName, t2.LastName, t2.Null AS PhoneNumber
FROM
Table2 AS t2
LEFT JOIN Table1 AS t1
ON
t2.FirstName = t1.FirstName
AND t2.LastName = t1.LastName
WHERE t1.FirstName Is Null;
Note I used UNION ALL
because it requires less work by the db engine so is therefore faster. Use just UNION
when you want the db engine to weed out duplicate rows. But, in this case, that would not be necessary ... unless duplicates exist separately within one or both of those tables.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…