I am trying to make a performant UNION (or JOIN) query between two tables:
tableA
+----+
| id |
+----+
| 1 |
| 2 |
| 7 |
+----+
tableB
+----+
| id |
+----+
| 1 |
| 2 |
| 9 |
+----+
Where it should produce the following output:
outputTable
+----+-----------+
| id | fromTable |
+----+-----------+
| 1 | TableA |
| 2 | TableA |
| 7 | TableA |
| 9 | TableB |
+----+-----------+
I want to reproduce the behavior of select tableA and then union (or join) the rows that aren’t on tableA or by another words union tableA and tableB with fromTable
priority on tableA. What’s the best way to accomplish this (performance wise)?
3
Answers
you can try something like that:
You can use a full join. For example:
Result:
See fiddle.
You can get the ids of
tableB
that don’t exist intableA
withEXCEPT
:and your final query would be:
or:
See the demo.