I have a VIEW which is SLOW. I don’t like the VIEW Statements as there are lot of JOINS and UNION.
Here is the view statement.
Create VIEW NewView AS
SELECT t2.* FROM Table1 t1
JOIN Table2 t2
ON t1.Column1 = t2.Column1 AND t1.Column2 = t2.Column2
WHERE t1.Column3 !='String'
UNION
SELECT t1.*, 'Add this string to the Last Column' FROM Table1 t1
LEFT JOIN Table2 t2
ON t1.Column1 = t2.Column1 AND t1.Column2 = t2.Column2
WHERE t2.Column1 is null OR t1.Column3 ='String'
ORDER BY Column 4
Basically the idea is if a record exists in Table1 and Table2, the record from Table2 should overlay the record from Table1. How can I optimize this?
I have a primary key id INT NOT NULL AUTO_INCREMENT PRIMARY KEY in both the tables but I am not sure how I can integrate that with the view. I want the view to have a primary key or composite key. I cannot use other columns as all the columns can have null and duplicate values.
You can join and compare, using an outer join, then use COALESCE to prefer T2 to T1.
To retain a unique key, and assuming your ID’s are all positive, you can make one table’s id’s negative.
EDIT:
For more complex rules on selecting which table has precidence, you can just use CASE statements…
(This does the same as above, but can be modified for different precidence rules.)