I have two tables with pretty much the same columns, except Table2 has three extra columns at the end Old_Column2, Old_Column3 and Column4. If a record exists in Table1 and Table2, Table2 overlays the record in Table1 otherwise display records from Table1. The query before the UNION takes care of that.
Now I also want the records which exists in Table2 but not in Table1. That’s the UNION clause. However with UNION the VIEW becomes slow.
I can’t use LEFT JOIN now. I was thinking of using a FULL JOIN instead but that might be slow too. What would be optimum way to do this?
To re-phrase Select all records from Table1, if the same record exists in Table2 overlay the record in the view. Add the new records where Old_Column2 and 3 equals to new
Here is the VIEW statement I am using.
CREATE VIEW AVIEW AS
SELECT
IF(U.Column1 IS NULL, L.Column1, U.Column1) Column1,
IF(U.Column1 IS NULL, L.Column2, U.Column2) Column2,
IF(U.Column1 IS NULL, L.Column3, U.Column3) Column3,
IF(U.Column1 IS NULL, NULL, U.Old_Column2) Old_Column2,
IF(U.Column1 IS NULL, NULL, U.Old_Column3) Old_Column3,
IF(U.Column1 IS NULL, NULL, U.Column4) Column4
FROM
Table1 L
LEFT JOIN Table2 U
ON L.Column1 = U.Column1 AND L.Column2 = U.Old_Column2 AND L.Column3 = U.Old_Column3
WHERE
U.Column1 IS NULL OR U.Column1 IS NOT NULL AND U.Column4 = 0
UNION
SELECT * FROM Table2 WHERE Old_Column2 = 'new' AND Old_Column3 = 'new' and Column4 = 0
Unfortunately you can’t do a
FULL OUTER JOINin MySQL. You have to simulate it by using 2 separateLEFT OUTER JOINqueries andunionthem together.One thing you can try to boost performance is to index Table2 on your Old_* columns and see if that predicate runs faster.