I have two tables
TABLE1
ID T3_ID PERIOD AGENT
1 1 2016 12
2 2 2016 13
3 3 2016 12
4 4 2015 12
and
TABLE2
ID T3_ID PERIOD PRODUCT
1 1 2016 'PRODUCT1'
2 3 2016 'PRODUCT2'
3 3 2015 'PRODUCT2'
I need to get all rows from both tables that match certain conditions and joining by T3_ID field. But in the case that in Table2 there isn't a matching row in Table2 for any T3_ID record in Table1, showing it anyway. The expected result in this example would be:
EXPECTED RESULT
ID T3_ID PERIOD AGENT PRODUCT
1 1 2016 12 'PRODUCT1'
2 2 2016 13 ''
3 3 2016 12 'PRODUCT2'
I already built a query, it works and shows expected results, but I wonder if there's a better way of doing this.
SELECT T1.*, '' AS PRODUCT FROM TABLE1 T1
WHERE T1.PERIOD='2016' AND T1.T3_ID NOT IN (SELECT T2.T3_ID FROM TABLE2 T2 WHERE T2.PERIOD='2016')
UNION
SELECT T1.*, T2.PRODUCT AS PRODUCT FROM TABLE1 T1
LEFT JOIN TABLE2 T2
ON T1.T3_ID=T2.T3_ID