Reputation: 31560
I have to maintain an application who's database is a little haywire and I had the following challenge to join 3 tables:
table1 timestamp,zid,aaa
table2 timestamp,zid,bbb
table3 id,some,other,data
So table 1 and 2 need to be joined and sorted on their timestamp columns. I also need to preserve table1's aaa and table2's bbb column and be able to distinguish whether its an aaa or a bbb. Then I need to join it to another table via their zid column.
Here is my working sql for this:
SELECT *
FROM
table3
LEFT JOIN
(
SELECT table1.timestamp AS timestamp,
table1.zid,
table1.aaa AS responses,
'aaas'
FROM table1
UNION ALL
SELECT table2.timestamp AS timestamp,
table2.zid,
table2.aaa AS responses,
'bbbs'
FROM table2
) aaasAndbbbs ON table3.id = aaasAndbbbs.zid
ORDER BY timestamp ASC;
The above sql does exactly what I want, but I want to know if there is a better way. Here I use the "aaas" column to distinguish whether it is an aaa or a bbb- which seems a little hacky. Is there a preferable way to do what I want?
Upvotes: 0
Views: 66
Reputation: 5307
The alternative would be to do each one separately and you will see the LEFT JOIN to table 3 is duplicated. I suspect however that if you look at the Execution plan for both your version and my version that they will be the same. The SQL Server Optimiser should be clever enough to figure out that both are doing the same thing and hence execute both in the same way. I find this slightly more readable than yours but that's my preference!
SELECT table1.timestamp AS timestamp,
table1.zid,
table1.aaa AS responses,
'aaas'
FROM table3
LEFT JOIN table1 on table3.id = table1.zid
UNION
SELECT table2.timestamp AS timestamp,
table2.zid,
table2.aaa AS responses,
'bbbs'
FROM table3
LEFT JOIN table1 on table3.id = table2.zid
ORDER BY timestamp ASC;
Upvotes: 0