I have three denormalized tables that I have to take at face value (data comes from some external resource). The three tables have different definitions, but they each describe the same object from different perspectives.
object1 A B object2 A object3 B C object4 C
The only commonality between these tables is their primary key. I can corral the IDs together using SELECT UNION SELECT, but the query seems relatively slow, even when each table has its PK field indexed. I could create a view to abstract this query, vw_object_ids, but it performs at the same speed. I thought I could add an index to materialize the view, but in SQL Server 2005, you can’t index views with UNIONs.
What I want is to have a master index of IDs be in sync with with the underlying data, which may get updated or deleted whenever. I guess I could accomplish this indefinitely with a crazy set of triggers or just settle for the speed of the unindexed view. But I just wanted to make sure I’m not missing any options or if this scenario has a name or is indicative of a pattern.
Thoughts?
Create a master table that contains only the ID:
and make all three tables to refer to that master table with
ON DELETE CASCADE.To populate the table for the first time, issue
To populate the table on a regular basis, create a trigger on each of three tables.
This trigger should try to insert the new
IDtomasterand silently fail onPRIMARY KEYviolation.To query, use:
This will use indexes efficienty.
To delete, use:
This will fire
ON DELETE CASCADEand delete records from all three tables if any.