I have some entity that is spread across three tables.
I have to get in a single result the following values:
- All the values that are in the first table but not on the second nor the third.
- All the values that are in the second table but not the third.
- All the values that are in the third table.
- Filtered by Col1.
For example, if I have the following data:
TableA
Id | Col1 | Col2 | Col3
1 | ValX | DatA | DatA
2 | ValZ | DatA | DatA
3 | ValX | DatA | DatA
5 | ValX | DatA | DatA
TableB
Id | Col1 | Col2 | Col3
1 | ValX | DatB | DatB
4 | ValZ | DatB | DatB
5 | ValX | DatB | DatB
6 | ValX | DatB | DatB
TableC
Id | Col1 | Col2 | Col3
1 | ValX | DatC | DatC
4 | ValZ | DatC | DatC
6 | ValX | DatC | DatC
7 | ValZ | DatC | DatC
If my filter is ValX
, I have to obtain this result:
Result
Id | Col1 | Col2 | Col3
1 | ValX | DatC | DatC <-- Notice I got Id 1 from TableC, not from TableA or TableB.
3 | ValX | DatA | DatA
5 | ValX | DatB | DatB
6 | ValX | DatC | DatC
The following code does exactly what I'm trying to accomplish, but I feel that it is ugly and inefficient:
SELECT Id, Col1, Col2, Col3
FROM TableA
WHERE Col1 = @Val AND
Id NOT IN (SELECT Id FROM TableB WHERE Col1 = @Val
UNION
SELECT Id FROM TableC WHERE Col1 = @Val)
UNION
SELECT Id, Col1, Col2, Col3
FROM TableB
WHERE Col1 = @Val AND
Id NOT IN (SELECT Id FROM TableC WHERE Col1 = @Val)
UNION
SELECT Id, Col1, Col2, Col3
FROM TableC
WHERE Col1 = @Val
.
How do you suggest I can improve or optimize this query?
.
@Val
is the same in each statement, how could you have a result that contains different values inCol1
? – pstrjds May 10 '12 at 19:54