select type,isnull(tid1.code,tid2.code) as Code
from MainTable mt
left join TableId1 tid1 on mt.Id1=tid1.Id1
left join TableId2 tid2 on mt.Id2=tid2.Id2
Avoid UNION ALL in SQL Server
-
29-06-2023 - |
Question
I have the following (simplified) problem. I have 3 Tables: MainTable, TableId1 and TableId2. They look like this
MainTable
+-------+------+-----+
| Type | Id1 | Id2 |
+-------+------+-----+
| a | 0 | 3 |
| b | 1 | 0 |
+-------+------+-----+
TableId1
+-----+------+
| Id1 | code |
+-----+------+
| 1 | abc |
+-----+------+
TableId2
+-----+------+
| Id2 | code |
+-----+------+
| 3 | xyz |
+-----+------+
I want to obtain the following result Set:
+-------+------+
| Type | code |
+-------+------+
| a | xyz |
| b | abc |
+-------+------+
I am right now using a UNION ALL, but it is not elegant and becomes a pain when my query becomes more complex and I have to edit it etc.
There has to me a way to avoid UNION ALL here I hope, can anyone show me?
Thanks!
La solution
Autres conseils
Use LEFT OUTER JOIN
and use where clause for Id1 and Id2 != 0.
Will post query in a minute.
You could try:
SELECT
mt.Type
,t1.Code
,t2.Code
FROM
MainTable mt
LEFT OUTER JOIN TableId1 t1
ON mt.Id1 = t1.Id1
LEFT OUTER JOIN TableId2 t2
ON mt.Id2 = t1.Id2
However this would give you:
+-------+------+------+
| Type | code | code |
+-------+------+------+
| a | null | xyz |
| b | abc | null |
+-------+------+------+
which may or may not be ideal for your scenario.
Define a view that gets data from all those 3 tables (using UNION ALL or not). This way you'll have to modify a single piece of code while your query "becomes complex".